首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正确地从Python2 md5库迁移到Python3hashlib

正确地从Python2 md5库迁移到Python3hashlib
EN

Stack Overflow用户
提问于 2017-07-09 00:57:09
回答 1查看 725关注 0票数 0

我试图在Django 1.11,Python3.5.2中集成第三方支付网关(CCAvenue)

第三方提供的参考代码使用不推荐的库md5加密文本。

代码语言:javascript
复制
from Crypto.Cipher import AES
import md5

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

def encrypt(plainText,workingKey):
    iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
    plainText = pad(plainText)
    encDigest = md5.new ()
    encDigest.update(workingKey)
    enc_cipher = AES.new(encDigest.digest(), AES.MODE_CBC, iv)
    encryptedText = enc_cipher.encrypt(plainText).encode('hex')
    return encryptedText

如何使用Python3的encrypt()库使上面的Python3方法兼容?你能贴出整个方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-09 01:11:34

警告:不要再使用密码或pycrypto了! 阅读更多

下面是一种与Python 3兼容的方法:

代码语言:javascript
复制
from binascii import hexlify, unhexlify
from Crypto.Cipher import AES
from hashlib import md5

from django.utils.encoding import force_bytes

iv = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
# for python 3.9 & pycryptodome, this need to be byte
iv = b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'

BS = 16


def _pad(data):
    return data + (BS - len(data) % BS) * chr(BS - len(data) % BS)


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


def encrypt(plain_text, working_key):
    plain_text = _pad(plain_text)
    enc_cipher = AES.new(md5(force_bytes(working_key)).digest(), AES.MODE_CBC, _iv)
    return hexlify(enc_cipher.encrypt(plain_text)).decode('utf-8')


def decrypt(cipher_text, working_key):
    encrypted_text = unhexlify(cipher_text)
    dec_cipher = AES.new(md5(force_bytes(working_key)).digest(), AES.MODE_CBC, _iv)
    return _unpad(dec_cipher.decrypt(encrypted_text).decode('utf-8'))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44992024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档