如何使用python ctr模式进行加密



我已经在nodejs中应用了加密算法,现在我需要使用python解密,我该如何做到这一点。

JS代码是-

const crypto = require('crypto');
const data = "Hello there, help me to decrypt using python"
let iv = 'N13FF0F4ACC4097M'
let key = '312s389g2r5b54rd'
const cp = crypto.createCipheriv('aes-128-ctr', key, iv)
let enc = cp.update(data, 'utf-8', 'base64') + cp.final('base64')
console.log(enc)

#output = 401Auq5PXMVzcbTJXl5hgLRccO8RSKFnB4VjsQuzkUNwJKMmwWHNqILIa1Q=

这是我在pyhton 中使用的代码

from Crypto.Cipher import AES
from Crypto.Util import Counter
data = "Hello there, help me to decrypt using python"
iv = b'N13FF0F4ACC4097M'
key = b'312s389g2r5b54rd'
ctr_e = Counter.new(64, prefix=iv)
cp = AES.new(key, AES.MODE_CTR, counter=ctr_e)
enc = cp.encrypt(data)
print(enc)

我在运用正确的方法时出错了。有人能帮助解决这个问题吗。

显示错误消息是因为您的Counter实现违反了(请参阅Counter(:

它必须保持len(前缀(+nbits//8+len(后缀(与底层块密码的块大小匹配。

在NodeJS代码中,既不使用前缀也不使用后缀,而是使用整个IV作为计数器值,即nBits等于128initial_value等于IV:的值

ctr_e = Counter.new(128, initial_value=int.from_bytes(b'N13FF0F4ACC4097M', 'big'))
cp = AES.new(key, AES.MODE_CTR, counter=ctr_e)

或者更短(见此处(:

cp = AES.new(key, AES.MODE_CTR, nonce=b'', initial_value=b'N13FF0F4ACC4097M')

通过这个修复(一个或另一个(,Python代码提供了NodeJS代码的密文。

最新更新