I was playing around PyCrypto's AES and DES implementation. Every time, I decrypted a cipher text, that I encrypted from a plain text, It gives out random strings.

I have tried the following:

from Crypto.Cipher import AES,DES
from Crypto import Random

iv_AES = Random.new().read(AES.block_size)
iv_DES = Random.get_random_bytes(8)

key_AES = 'abcdefghijklmnop'
key_DES = 'abcdefgh'

aes = AES.new(key_AES,AES.MODE_CFB,iv_AES)
aes1 = AES.new(key_AES,AES.MODE_CFB,iv_AES)
des = DES.new(key_DES,DES.MODE_CFB,iv_DES)
des1 = DES.new(key_DES,DES.MODE_CFB,iv_DES)

plaintext = 'Hello! World'

print plaintext == aes.decrypt(aes.encrypt(plaintext))
print plaintext == des.decrypt(des.encrypt(plaintext))
print plaintext == aes1.decrypt(aes.encrypt(plaintext))
print plaintext == des1.decrypt(des.encrypt(plaintext))

Result:

False
False
True
True

I don't understand why this is happening.

Can you please explain what is actually happening here, and why is it so?

有帮助吗?

解决方案

From the PyCrypto documentation:

That also means that you cannot reuse an object for encrypting or decrypting other data with the same key.

The issue is that you will have to reinitialize your cipher, or - probably better - to construct separate object instances for encryption and decryption.

from Crypto.Cipher import AES,DES
from Crypto import Random

iv_AES = Random.new().read(AES.block_size)
iv_DES = Random.get_random_bytes(8)

key_AES = 'abcdefghijklmnop'
key_DES = 'abcdefgh'

aese = AES.new(key_AES,AES.MODE_CFB,iv_AES)
aesd = AES.new(key_AES,AES.MODE_CFB,iv_AES)
dese = DES.new(key_DES,DES.MODE_CFB,iv_DES)
desd = DES.new(key_DES,DES.MODE_CFB,iv_DES)

plaintext = 'Hello! World'

print plaintext == aesd.decrypt(aese.encrypt(plaintext))
print plaintext == desd.decrypt(dese.encrypt(plaintext))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top