我需要使用一个对象在一个类文件中解密2个密码。解密适用于第一个密码。它为第二次密码解密提供了垃圾值。
from Crypto.Cipher import AES
obj = AES.new(b'This is a key123', AES.MODE_CFB, b'This is a key123')
ciphertext = obj.encrypt(b'devuser')
a = b'R\xa9\xd2)[\x9a\x99\xd9' #devuser1
print("Encrypt: ",ciphertext)
obj2 = AES.new(b'This is a key123', AES.MODE_CFB, b'This is a key123')
print ("Decrypt: ", obj2.decrypt(ciphertext))
print ("Decrypt: ", obj2.decrypt(a))
如果我使用2个不同的对象进行解密,它工作正常。
from Crypto.Cipher import AES
obj = AES.new(b'This is a key123', AES.MODE_CFB, b'This is a key123')
ciphertext = obj.encrypt(b'devuser')
a = b'R\xa9\xd2)[\x9a\x99\xd9' #devuser1
print("Encrypt: ",ciphertext)
obj2 = AES.new(b'This is a key123', AES.MODE_CFB, b'This is a key123')
obj3 = AES.new(b'This is a key123', AES.MODE_CFB, b'This is a key123')
print ("Decrypt: ", obj2.decrypt(ciphertext))
print ("Decrypt: ", obj3.decrypt(a))
我们是否只能使用obj2
来解密?
答案 0 :(得分:0)
密码对象是有状态的,这意味着您无法重复使用对象来加密或解密具有相同密钥的其他数据。
答案 1 :(得分:0)
没有。您使用的是CFB mode,它需要使用州,并使obj.encrypt
和obj.decrypt
不是纯函数:
In [1]: from Crypto.Cipher import AES
In [2]: obj = AES.new(b'This is a key123', AES.MODE_CFB, b'This is a key123')
In [3]: obj.encrypt(b'devuser')
Out[3]: b'R\xa9\xd2)[\x9a\x99'
In [4]: obj.encrypt(b'devuser')
Out[4]: b'\x8c)l\xcc\t<\x82'
In [5]: obj.encrypt(b'devuser')
Out[5]: b'\xae\xea)dv6\x82'
In [6]: obj.encrypt(b'devuser')
Out[6]: b'\xe9\xd5\xc5kH+\x05'
In [7]: obj.encrypt(b'devuser')
Out[7]: b'\xf3\x8b\xaf\xe7\xac\xca*'
CFB模式可能不是您的特定应用程序的最佳模式,因为它只允许部分明文被攻击者破坏,其余部分完好无损:
In [1]: from Crypto.Cipher import AES
In [2]: aes1 = AES.new(b'This is a key123', AES.MODE_CFB, b'This is a key123')
In [3]: aes2 = AES.new(b'This is a key123', AES.MODE_CFB, b'This is a key123')
In [4]: plaintext = b'0123456789' * 20
In [5]: plaintext
Out[5]: b'01234567890123456789012345678901234567890123456789012345678901234567
890123456789012345678901234567890123456789012345678901234567890123456789012345
678901234567890123456789012345678901234567890123456789'
In [6]: ciphertext = aes1.encrypt(plaintext)
In [7]: corrupted = ciphertext[:80] + b'?' * 20 + ciphertext[120:]
In [8]: corrupted_plaintext = aes2.decrypt(corrupted)
In [9]: corrupted_plaintext
Out[9]: b'01234567890123456789012345678901234567890123456789012345678901234567
890123456789\x11\xfe\x12z\x04[\xe3N\x8b)a\x87gF\xc4XIIII\xe4L:?\xe2.\x04cx\xa3
\xd2\xf6r>W\x066789012345678901234567890123456789012345678901234567890123456789'