1

I've looked at the AES - Encryption with Crypto (node-js) / decryption with Pycrypto (python) post since I'm trying to do the complete opposite but I can't seem to get it right. Here's what I've tried so far ...

Python encryption

import base64
from Crypto import Random
from Crypto.Cipher import AES

text_file = open("cryptic.txt", "w")

pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) 
unpad = lambda s : s[:-ord(s[len(s)-1:])]

plaintxt = 'dolladollabillzz'
iv = Random.new().read( AES.block_size )
print AES.block_size
key = 'totallyasecret!!'
cipher = AES.new(key=key, mode=AES.MODE_CBC, IV=iv)
encrypted = base64.b64encode(iv + cipher.encrypt(plaintxt))

text_file.write(encrypted)
text_file.close()

Node.js decryption

var fs = require('fs');
var crypto = require('crypto');
var Buffer = require('buffer').Buffer;

var algorithm = 'aes-128-cbc';
var key = new Buffer('totallyasecret!!', 'binary');

var cryptic = fs.readFileSync('./cryptic.txt', 'base64');
var iv = cryptic.slice(0, 16);
var ciphertext = cryptic.slice(16);

var decipher = crypto.createDecipheriv(algorithm, key, iv);
var decrypted = [decipher.update(ciphertext)];
decrypted.push(decipher.final('utf8'));
var finished = Buffer.concat(decrypted).toString('utf8');
console.log(finished);

Every time I try to run the Node.js decryption, I end up with the error message:

Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length

1 Answer 1

0

Since the IV is randomly generated in Python, it can contain any possible byte value. Some of those byte values are not valid UTF-8 characters (e.g. multiple bytes are one character) and may result in wrongly sliced off IV, so that the actual ciphertext is slightly shifted.

Since AES is a block cipher, the bits have to line up to be properly decrypted. This should fix it:

var cryptic = fs.readFileSync('./cryptic.txt', 'utf8');
cryptic = new Buffer(cryptic, 'base64');
var iv = cryptic.slice(0, 16);
var ciphertext = cryptic.slice(16);

This changes a binary string to a Buffer which perfectly handles binary data.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the suggestion @Artjom but I'm still receiving the same 'wrong final block length' error. I've also tried using 'binary' in the readFileSync but the result is the same as well.
Can you provide a ciphertext for testing?
Sure, I ran my python script exactly the way it is in my post and came up with the resulting ciphertext Ew2rBvVohbJdFp9D3rBmIAGQWekoL3W3JuF6sQc4DRQ=

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.