【问题标题】:can somebody tell me what went wrong, when I am trying to decrypt the ciphertext that I encrypted, it tells me that my padding is incorrect有人可以告诉我出了什么问题,当我试图解密我加密的密文时,它告诉我我的填充不正确
【发布时间】:2021-01-30 15:13:20
【问题描述】:

当试图解密我的明文时,它给了我一个值错误。

mesg = b'b235dd55aae34e97a054b05c09777e18'

decipher = AES.new(key,AES.MODE_CBC,iv)
plaintext = decipher.decrypt(mesg)
truetext = unpad(plaintext,block_size=16)
print(hexa(truetext).decode())

输出表明

ValueError: Padding is incorrect.

即使我自己使用加密明文

plaintext = b"hello world"
ciphertext = cipher.encrypt(pad(plaintext,16))
print(hexa(ciphertext).decode())

这是我的简单加密/解密的样子

#Pycryptodome
#unable to decrypt, padding problem
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from binascii import hexlify as hexa


key = get_random_bytes(16)  
iv = get_random_bytes(16)
cipher = AES.new(key,AES.MODE_CBC,iv)

plaintext = b"hello world"
ciphertext = cipher.encrypt(pad(plaintext,16))
print(hexa(ciphertext).decode())

mesg = b'b235dd55aae34e97a054b05c09777e18'

decipher = AES.new(key,AES.MODE_CBC,iv)
plaintext = decipher.decrypt(mesg)
truetext = unpad(plaintext,block_size=16)
print(hexa(truetext).decode())

【问题讨论】:

  • 您生成一个随机密钥并尝试用它解密一个加密的 (mesg) 值。尝试解密 ciphertext 而不是 mesg
  • 我想查看/尝试解密已编码的密文。我正在上课并想尝试它,作为实际执行之前的测试运行,似乎我可能需要尝试其他人正在使用的库。
  • 在程序开始时,您将生成一个带有key = get_random_bytes(16) 的随机密钥。每次运行程序时,您都会获得一个新的随机密钥。为了能够解密消息,您需要使用与加密时相同的密钥进行解密。当您对要解密的消息进行硬编码并同时生成一个新密钥时,无法解密硬编码的消息 - 因为它是使用先前运行的另一个密钥加密的。您需要保存用于加密的密钥,以便您有 if 用于解密。

标签: python encryption aes padding


【解决方案1】:

请改用此代码。

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
from binascii import hexlify as hexa


key = get_random_bytes(16)  
iv = get_random_bytes(16)
cipher = AES.new(key,AES.MODE_CBC,iv)

plaintext = b"hello world"
ciphertext = cipher.encrypt(pad(plaintext,16))
print(hexa(ciphertext).decode())

# mesg = b'b235dd55aae34e97a054b05c09777e18' 
# can't be decrypted with different key/iv pair 

decipher = AES.new(key,AES.MODE_CBC,iv)
plaintext = decipher.decrypt(ciphertext)  # decrypt ciphertext instead
truetext = unpad(plaintext,block_size=16)
print(hexa(truetext).decode())

您的问题似乎是(因为我不知道 msg 的密钥和 iv)是当使用 pkcs7 解密和取消填充 msg 时,填充不正确,因为 pkcs7 检查是否有消息之后正确填充(检查wikipedia),如果消息未正确填充,则抛出错误。总而言之,plaintext 使用特定密钥/iv 对加密,它的密文也必须使用相同的密钥/iv 对解密在加密期间,否则您的消息将被解密为废话或导致错误的填充错误。

【讨论】:

  • 为什么要推荐一个不同的库而实际上却没有让它更安全? 1.你应该明确IV应该在加密过程中生成并与密文一起发送。 2. 为什么不通过AES-GCM或者添加MAC来添加认证?
  • @ArtjomB。我并不是要推荐一个不同的库,只是因为我习惯了cryptography 模块并且不想更改模式,因为问题是使用没有 MAC 的 CBC(不想让事情变得更复杂)。但我会编辑以使事情更清楚,必须使用相同的密钥/iv 对,我认为最后一句很清楚,谢谢。
猜你喜欢
  • 2014-11-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
相关资源
最近更新 更多