Python pycrypto 加密与解密

时间:2021-12-13 14:56:49

参考: python 使用 pycrypto‎ 实现 AES 加密解密

参考: 分组对称加密模式:ECB/CBC/CFB/OFB

代码示例 :

import hashlib
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex def encrypt(key, text):
# 密钥 key 的长度必须为 16(AES-128), 24(AES-192), 32(AES-256) Bytes,
# 所以直接将用户提供的 key md5 变为 32 位.
key_md5 = hashlib.md5(key).hexdigest() # AES.MODE_CFB 是分组加密模式, b'0000000000000000'
# 是初始化向量 IV, 16 位要求, 可以看做是另一个密钥. 在部分分组模式中需要.
cipher = AES.new(key_md5, AES.MODE_CFB, b'0000000000000000') # AES 要求需要加密的内容长度为 16 的倍数, 当密文长度不够的时候使用 '\0' 补足.
ntext = text + ('\0' * (16-(len(text) % 16))) # b2a_hex 转换一下, 默认加密后的字符串有很多特殊字符.
return b2a_hex(cipher.encrypt(ntext)) def decrypt(key, text):
key_md5 = hashlib.md5(key).hexdigest()
cipher = AES.new(key_md5, AES.MODE_CFB, b'0000000000000000')
t = cipher.decrypt(a2b_hex(text))
return t.rstrip('\0') # 基于类的实现:
class MyCrypt(object):
def __init__(self, key):
self.key = hashlib.md5(key).hexdigest()
self.mode = AES.MODE_CFB
self.salt = b'0000000000000000' def encrypt(self, text):
cipher = AES.new(self.key, self.mode, self.salt)
ntext = text + ('\0' * (16-(len(text) % 16)))
return b2a_hex(cipher.encrypt(ntext)) def decrypt(self, text):
cipher = AES.new(self.key, self.mode, self.salt)
t = cipher.decrypt(a2b_hex(text))
return t.rstrip('\0')