AES.new(key, AES.MODE_CFB, iv)然后,加密
cipher.encrypt(str)
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Hash import SHA256
class MyAesEncrypt:
cipher = None
# 初始化 ,传入Key,用key的sha256作AES密钥,再取密钥的前**位的哈希作初始向量
def __init__(self, key, iv=None):
key = bytes(key, encoding="UTF-8")
key = SHA256.new(data=key).digest()
if (iv == None):
iv = SHA256.new(data=key).digest()[:AES.block_size]
# self.peepBytes(key, "key")
# self.peepBytes(iv, "iv")
self.cipher = AES.new(key, AES.MODE_CFB, iv)
# 静态方法,查看密钥
@staticmethod
def peepBytes(a, str="peepBytes"):
print(str, end=":")
for i in a:
print("%02x" % i, end="")
print("")
# 加密方法
def Encrypt(self, str):
str = bytes(str, encoding="UTF-8")
str = pad(str, AES.block_size)
return self.cipher.encrypt(str)
class MyAesDecrypt:
uncipher = None
def __init__(self, key, iv=None):
key = bytes(key, encoding="UTF-8")
key = SHA256.new(data=key).digest()
if (iv == None):
iv = SHA256.new(data=key).digest()[:AES.block_size]
self.uncipher = AES.new(key, AES.MODE_CFB, iv)
# 解密方法
def Decrypt(self, byte_str):
str = unpad(self.uncipher.decrypt(byte_str), AES.block_size)
return str.decode("UTF-8")
if __name__ == "__main__":
a = MyAesEncrypt("hello")
str = a.Encrypt("?? ?¥?hello world")
b = MyAesDecrypt("hello")
print(b.Decrypt(str))
原文:https://www.cnblogs.com/MarmaladeCat/p/62e365fd71aa50eff2bb6aebde637d81.html