为什么AES.decrypt没有返回原始文本?

时间:2012-07-24 11:21:38

标签: python aes pycrypto

我正在尝试使用 AES 将一些密码安全地存储在自制密码保险箱中,但出于某种原因,我没有从AES.decrypt获取原始数据。这是我正在测试的代码:

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)

它是输出:

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

我正在使用密码反馈模式,因为我希望能够对任意长度的字符串进行加密和解密,而且我不会因为我只是计划而逐字节地工作而烦恼我加密小字符串。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:7)

因为您使用相同的aes对象进行加密和解密。加密后,初始值发生了变化。因此,您没有使用相同的初始值进行解密。以下工作(重新声明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)

答案 1 :(得分:0)

不确定原因,但这有效:

key = b"JG9A90cqiveJ8K7n"
mode = AES.MODE_CFB
iv = b"g4vhFIR1KncRIyvO"

text = 'This is some text that will be encrypted'

aes_enc = AES.new(key, mode, iv)
enc = aes_enc.encrypt(text)

aes_dec = AES.new(key, mode)
dec = aes_dec.decrypt(iv + enc)

assert text == dec[16:]

我也必须查看iv和padding的细节:)

修改

请参阅http://packages.python.org/pycrypto/Crypto.Cipher.blockalgo-module.html#MODE_CFB