[英]PyCrypto AES encryption not working as expected
I am creating a Python function to perform counter mode encryption using the PyCrypto module. 我正在创建一个Python函数来使用PyCrypto模块执行计数器模式加密。 I am aware of the builtin, but want to implement it myself.
我知道内置,但想自己实现它。
I'm trying Test Vector #1 from RFC 3686 , and have the correct Counter Block and the correct Key in ASCII form. 我正在尝试RFC 3686中的测试向量#1 ,并且具有正确的计数器块和ASCII形式的正确密钥。 But when I encrypt the Counter Block using the Key, I don't get the expected Key Stream.
但是当我使用密钥加密计数器块时,我没有得到预期的密钥流。
The relevant parts of my code: 我的代码的相关部分:
cipher = AES.new(key)
ctr_block = iv + nonce + ctr
key_stream = base64.b64decode(cipher.encrypt(ctr_block))
I can provide more code if needed, but I'm not sure how because ctr_block
and key
have many question mark characters when I print them. 如果需要,我可以提供更多代码,但是我不确定因为
ctr_block
和key
在打印时有很多问号字符。
Why am I not getting the expected answer? 为什么我没有得到预期的答案? It seems like everything should go right.
似乎一切都应该正确。 Perhaps I made some mistake with the encoding of the string.
也许我对字符串的编码犯了一些错误。
Edit 编辑
Self-contained code: 自包含代码:
from Crypto.Cipher import AES
import base64
def hex_to_str(hex_str):
return str(bytearray([int(n, 16) for n in hex_str.split()]))
key = hex_to_str("AE 68 52 F8 12 10 67 CC 4B F7 A5 76 55 77 F3 9E")
iv = hex_to_str("00 00 00 00 00 00 00 00")
nonce = hex_to_str("00 00 00 30")
ctr = hex_to_str("00 00 00 01")
cipher = AES.new(key)
ctr_block = iv + nonce + ctr
key_stream = base64.b64decode(cipher.encrypt(ctr_block))
print "".join([hex(ord(char)) for char in key_stream])
# 0xd90xda0x72
First, use byte strings: 首先,使用字节串:
In [14]: keystring = "AE 68 52 F8 12 10 67 CC 4B F7 A5 76 55 77 F3 9E"
In [15]: keystring.replace(' ', '').decode('hex')
Out[15]: '\xaehR\xf8\x12\x10g\xccK\xf7\xa5vUw\xf3\x9e'
Second, you shouldn't use base64. 其次,你不应该使用base64。
First, the correct CTR block order is nonce + iv + ctr
. 首先,正确的CTR块顺序是
nonce + iv + ctr
。 Second, that base64.b64decode
call is wrong: cipher.encrypt
produces a decoded string. 其次,
base64.b64decode
调用错误: cipher.encrypt
生成一个已解码的字符串。 After these two fixes your code prints 0xb70x600x330x280xdb0xc20x930x1b0x410xe0x160xc80x60x7e0x620xdf
which seems to be a correct key stream. 完成这两个修复后,您的代码将打印出
0xb70x600x330x280xdb0xc20x930x1b0x410xe0x160xc80x60x7e0x620xdf
,这似乎是一个正确的密钥流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.