【问题标题】:Correctly migrate from Python 2 md5 library to Python 3 hashlib in Flask web application for CCAvenue integration在 Flask Web 应用程序中正确从 Python 2 md5 库迁移到 Python 3 hashlib 以进行 CCAvenue 集成
【发布时间】:2019-05-15 09:30:44
【问题描述】:

我正在尝试在 Flask 0.12.2、Python 3.6.1 中集成第 3 方支付网关 (CCAvenue)。

第 3 方提供的参考代码使用已弃用的库 md5 对文本进行加密。

我在Existing Solution in Django 中找到了迁移解决方案。但是,我需要相同的 Flask 版本代码。

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: python python-3.x flask hashlib ccavenue


【解决方案1】:

我已经找到了解决方案,这里是代码

from Crypto.Cipher import AES
import hashlib
from binascii import hexlify, unhexlify

def pad(data):
    length = 16 - (len(data) % 16)
    data += chr(length)*length
    return data

def unpad(data):
    return data[0:-ord(data[-1])] 

def encrypt(plainText, workingKey):
    iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
    plainText = pad(plainText)
    bytearrayWorkingKey = bytearray()
    bytearrayWorkingKey.extend(map(ord, workingKey))
    enc_cipher = AES.new(hashlib.md5(bytearrayWorkingKey).digest(), AES.MODE_CBC, iv)
    return hexlify(enc_cipher.encrypt(plainText)).decode('utf-8')

def decrypt(cipherText, workingKey):
    iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
    encryptedText = unhexlify(cipherText)
    bytearrayWorkingKey = bytearray()
    bytearrayWorkingKey.extend(map(ord, workingKey))
    decCipher = AES.new(hashlib.md5(bytearrayWorkingKey).digest(), AES.MODE_CBC, iv)
    return unpad(decCipher.decrypt(encryptedText).decode('utf-8'))

【讨论】:

    【解决方案2】:

    添加对我有用的@prash 解决方案的更新。 iv was of type str

    from Crypto.Cipher import AES
    import hashlib
    from binascii import hexlify, unhexlify
    
    def pad(data):
        length = 16 - (len(data) % 16)
        data += chr(length)*length
        return data
    
    def unpad(data):
        return data[0:-ord(data[-1])] 
    
    def encrypt(plainText, workingKey):
        iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'.encode("utf-8")
        plainText = pad(plainText)
        bytearrayWorkingKey = bytearray()
        bytearrayWorkingKey.extend(map(ord, workingKey))
        enc_cipher = AES.new(hashlib.md5(bytearrayWorkingKey).digest(), AES.MODE_CBC, iv)
        return hexlify(enc_cipher.encrypt(plainText.encode("utf-8"))).decode('utf-8')
    
    def decrypt(cipherText, workingKey):
        iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
        encryptedText = unhexlify(cipherText)
        bytearrayWorkingKey = bytearray()
        bytearrayWorkingKey.extend(map(ord, workingKey))
        decCipher = AES.new(hashlib.md5(bytearrayWorkingKey).digest(), AES.MODE_CBC, iv)
        return unpad(decCipher.decrypt(encryptedText).decode('utf-8'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2016-01-29
      • 1970-01-01
      相关资源
      最近更新 更多