1
votes

I have applied the the encryption algorithm in nodejs and now I need to decrypt the same using python how would I be able to do this.

The JS code is -

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=

Here is code i used in 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)

I am getting error in applying the correct way. Can anyone help to resolve this issue.

1
Can. you show the errors you're getting? - wkl
ValueError: Size of the counter block (24 bytes) must match block size (16) - Abhineet Kumar
This is the error. TypeError: CTR counter function returned string not of length 16 - D.L

1 Answers

1
votes

The error message is displayed because your Counter implementation violates (see Counter):

It must hold that len(prefix) + nbits//8 + len(suffix) matches the block size of the underlying block cipher.

In the NodeJS code neither a prefix nor a suffix is used, but the whole IV as counter value, i.e. nBits equals 128 and initial_value equals the value of the IV:

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

Alternatively and shorter (see here):

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

With this fix (one or the other), the Python code provides the ciphertext of the NodeJS code.