将AES生成的十六进制从aes-jsJavascript解密为pycryptodomePython

问题描述

因此,我试图解密用Python用JS加密的字符串。我使用了aes-js库。我得到这个:caba6777379a00d12dcd0447015cd4dbcba649857866072d。这是我的JS代码

var key = aesjs.utils.utf8.toBytes("ThisKeyIs16Bytes");
console.log(`Key (bytes): ${key}`);

var text = 'psst... this is a secret';
var textBytes = aesjs.utils.utf8.toBytes(text);

var aesCtr = new aesjs.ModeOfOperation.ctr(key,new aesjs.Counter(5));
var encryptedBytes = aesCtr.encrypt(textBytes);

var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(`Hex: ${key}`);

我已经在python中尝试了一些东西,但这是我目前拥有的:

from Crypto.Cipher import AES

ciphered_data = bytearray.fromhex('caba6777379a00d12dcd0447015cd4dbcba649857866072d')
key = b'ThisKeyIs16Bytes'

cipher = AES.new(key,AES.MODE_CTR)
original_data = cipher.decrypt(ciphered_data)
print(original_data.decode("utf-8",errors="ignore"))

但是我只是一团糟。=*լ☻ve↕-:tQɊ#¶

解决方法

使用CTR模式。在Pyton代码中,缺少计数器的初始化功能,即正确的起始值的定义,例如

...
cipher = AES.new(key,AES.MODE_CTR,nonce = b'',initial_value = 5)
...

或使用Counter对象:

from Crypto.Util import Counter
...
counter = Counter.new(128,initial_value = 5)
cipher = AES.new(key,counter = counter)
...

通过这两个更改之一,解密就起作用了。