【问题标题】:Why is AES.decrypt not returning my original text?为什么 AES.decrypt 不返回我的原始文本?
【发布时间】:2012-07-24 11:21:38
【问题描述】:

我正在尝试使用 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)

它的输出:

原文:099e17130a9c796c8b7f21f269a790e877c7f49b6a39deda33d4e7b63b80c049
加密:71006ff5dc695a32c020dbb27c45b4861ec10a76e40d349bf078bca56b57d5bb
解密:2683455f4ae01e3cd1cba6c2537712fee8783621f32c865b8d4526130ff0096d

我使用密码反馈模式是因为我希望能够加密和解密任何长度的字符串,而且它不会打扰我,因为我只是在计划关于加密小字符串。

我在这里做错了什么?

【问题讨论】:

  • 对于使用相同密钥的每个加密,IV 必须不同(读取:随机)。不要使用静态 IV,因为这会使密码具有确定性,并允许攻击者在观察到多个密文时推断出明文。这称为多次填充(或two-time pad)。 IV 不是秘密,因此您可以将其与密文一起发送。通常,它只是简单地添加到密文中,并在解密之前被切掉。

标签: python aes pycrypto


【解决方案1】:

因为您使用相同的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)

【讨论】:

  • 很奇怪。我正在关注an example in the official documentation,它不会重新创建密码。我想在某处提到必须仅使用一次,但我没有发现它。
  • @Codemonkey 似乎只提到 Crypto.Cipher 的以下内容:IV: Contains the initial value which will be used to start a cipher feedback mode. After encrypting or decrypting a string, this value will reflect the modified feedback text; it will always be one block in length. It is read-only, and cannot be assigned a new value.
【解决方案2】:

不知道为什么,但这有效:

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 和填充的详细信息 :)

编辑:

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

【讨论】:

  • IV 需要与密文一起存储才能解密。这通常通过简单地将 IV 附加到密文来完成。我的假设是您的示例有效,因为您执行了将 IV 预先附加到密文 (aes_dec.decrypt(iv + enc)) 的手动步骤。当我在 Python 2.7.11 上尝试时,您的示例不起作用
猜你喜欢
  • 2019-10-16
  • 2021-02-24
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多