PyCrypto AES CBC加解密结果不一致的解决

使用了CBC带偏移量的加密算法,pkcs5/7填充

结果解密后的字串和加密前不一样,网上到处都没搜到原因
后来发现,cipher对象只能用一次,同时调用两次cipher去对同一个东西加密,得到的结果不一样
所以解密时,必须重新new一个cipher。下面是修正后的代码


# coding: utf-8
from Crypto.Cipher import AES
import base64

BS = AES.block_size
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode('utf-8')
unpad = lambda s : s[0:-s[-1]]

key = b"a"*32
text = b'to be encrypted'
IV = b'huabulajichanmao'

cipher = AES.new(key, mode=AES.MODE_CBC, IV=IV)
cipher2 = AES.new(key, mode=AES.MODE_CBC, IV=IV)  # 加密和解密,cipher对象只能用一次

print(text)
encrypted = pad(text)
print(encrypted)
encrypted = cipher.encrypt(encrypted)
print(encrypted)
encrypted = base64.b64encode(encrypted)
print(encrypted)  # will be something like 'f456a6b0e54e35f2711a9fa078a76d16'

decrypted = base64.b64decode(encrypted)
print(decrypted)
decrypted = cipher2.decrypt(decrypted)
print(decrypted)  # will be 'to be encrypted'
decrypted = unpad(decrypted)
print(decrypted)

输出如下

b'to be encrypted'
b'to be encrypted\x01'
b'l\x19\x9aCj\xe7+~\x1d\x07\xd4\x16\xfb\x91"~'
b'bBmaQ2rnK34dB9QW+5Eifg=='
b'l\x19\x9aCj\xe7+~\x1d\x07\xd4\x16\xfb\x91"~'
b'to be encrypted\x01'
b'to be encrypted'
发布了25 篇原创文章 · 获赞 22 · 访问量 9333

猜你喜欢

转载自blog.csdn.net/qq_27884799/article/details/93173921