openssl -aes-128-ecb加密与python Crypto.Cipher AES加密不匹配

记录器

我正在尝试加密16字节的字符串“黎明时攻击!” 使用带有密码“黄色潜水艇”的AES-128。

在python中:

from Crypto.Cipher import AES
from base64 import b64encode

plaintext = 'Attack at dawn!!'
obj = AES.new("yellow submarine", AES.MODE_ECB)
ciphertext = obj.encrypt(plaintext)

print(b64encode(ciphertext).decode())

密文为'kBKTLPWpU7Dpf / TiGo6p3w =='

现在在终端中使用openssl。plain.txt是一个文本文件,包含字符串“黎明时攻击!!”:

openssl enc -aes-128-ecb -nosalt -nopad -pass pass:"yellow submarine" -in plain.txt -out cipher.txt -a

这将返回“ X + fHjd97VRZLbH + BCgu6Xw ==”作为密文。

为什么它们不一样?

我曾尝试阅读文档或示例,但在互联网上找不到任何有用的东西。我试过更改openssl命令中的选项。我不知道该如何解决这个问题。

记录器

在python中,使用Crypto.AES的AES进行加密.Cipher获取一个密钥(16个字节的字符串)和一个纯文本(16个字节),并输出一个密文(16个字节)。

要使用OpenSSL达到相同的目的,您首先需要使用禁用盐分和填充,-nosalt-nopad确保它需要16字节的输入并返回16字节的输出。提供密码会导致OpenSSL派生自己的密钥。要覆盖此-K选项,请使用选项(其中密钥必须以十六进制给出)。或者,输入密码并指定-p将使OpenSSL吐出它使用的密钥。

  • 使用键“黄色潜水艇”:

蟒蛇

from Crypto.Cipher import AES
from base64 import b64encode

plaintext = 'Attack at dawn!!'
obj = AES.new("yellow submarine", AES.MODE_ECB)
ciphertext = obj.encrypt(plaintext)

print(b64encode(ciphertext).decode())

的openssl

enc -aes-128-ecb openssl enc -aes-128-ecb -nosalt -nopad -K 79656c6c6f77207375626d6172696e65 -in plain.txt -out cipher.txt -a

这两种方法都给出了“ kBKTLPWpU7Dpf / TiGo6p3w ==”。

  • 使用OpenSSL密码“黄色潜水艇”:

    openssl enc -aes-128-ecb -nosalt -nopad -p -pass通过:“黄色潜水艇” -in plain.txt -out cipher.txt -a

这会将密钥输出为'A35EC217E15C1DD258201A184814897C'。要将其与Crypto.Cipher一起使用,我们首先需要将其转换为十六进制。

from Crypto.Cipher import AES
from base64 import b64encode

hex_key = 'A35EC217E15C1DD258201A184814897C'
key = bytes.fromhex(hex_key)

plaintext = 'Attack at dawn!!'
obj = AES.new(key, AES.MODE_ECB)
ciphertext = obj.encrypt(plaintext)

print(b64encode(ciphertext).decode())

这两种方法都给出'X + fHjd97VRZLbH + BCgu6Xw =='。

  • 要回答的最后一个问题:你应该有更紧密地阅读手册OpenSSL的ENC,并发现了-p-P-k选项。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章