Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is AES.decrypt not returning my original text?

I'm trying to use AES to safely store some passwords in a home-made password safe, but for some reason I'm not getting the original data back from AES.decrypt. Here is the code I'm testing with:

from Crypto.Cipher import AES
from Crypto.Hash import SHA256

def sha1(text):
    s = SHA256.new()
    s.update(text)
    return s.hexdigest()

aes = AES.new('JG9A90cqiveJ8K7n', AES.MODE_CFB, 'g4vhFIR1KncRIyvO')

text = 'This is some text that will be encrypted'
encrypted_text = aes.encrypt(text)
decrypted_text = aes.decrypt(encrypted_text)

print 'Original:\t' + sha1(text)
print 'Encrypted:\t' + sha1(encrypted_text)
print 'Decrypted:\t' + sha1(decrypted_text)

It's output:

Original:   099e17130a9c796c8b7f21f269a790e877c7f49b6a39deda33d4e7b63b80c049
Encrypted:  71006ff5dc695a32c020dbb27c45b4861ec10a76e40d349bf078bca56b57d5bb
Decrypted:  2683455f4ae01e3cd1cba6c2537712fee8783621f32c865b8d4526130ff0096d

I'm using the cypher feedback mode because I want to be able to encrypt and decrypt strings of any length, plus it won't bother me that it works on a byte-by-byte basis since I'm only planning on encrypting small strings.

What am I doing wrong here?

like image 759
Hubro Avatar asked Dec 27 '22 20:12

Hubro


1 Answers

Because you are using the same aes object for encryption and decryption. After the encrypt the initial value has changed. So you are not using the same initial value for decrypting. The following does work (redeclaring aes):

from Crypto.Cipher import AES
from Crypto.Hash import SHA256

def sha1(text):
    s = SHA256.new()
    s.update(text)
    return s.hexdigest()

aes = AES.new('JG9A90cqiveJ8K7n', AES.MODE_CFB, 'g4vhFIR1KncRIyvO')

text = 'This is some text that will be encrypted'
encrypted_text = aes.encrypt(text)

aes = AES.new('JG9A90cqiveJ8K7n', AES.MODE_CFB, 'g4vhFIR1KncRIyvO')
decrypted_text = aes.decrypt(encrypted_text)

print 'Original:\t' + sha1(text)
print 'Encrypted:\t' + sha1(encrypted_text)
print 'Decrypted:\t' + sha1(decrypted_text)
like image 131
klennepette Avatar answered Dec 29 '22 09:12

klennepette