I’m symmetrically encrypting data using node.js code, that I’ll decrypt using the openssl command in a bash script.
I have encrypt/decrypt functions in both environments that work as expected, but encrypting in one and decrypting in the other seems not to work.
I tried to make sure the methods used are completely the same (using aes-256-cbc, 10000 iterations, encoding, …) but methods are still incompatible.
Encrypt/decrypt in node:
const crypto = require('crypto');
const { Buffer } = require('buffer');
function encrypt(text, password) {
const salt = crypto.randomBytes(16);
const key = crypto.pbkdf2Sync(password, salt, 10000, 32, 'sha256');
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(text, 'utf8', 'base64');
encrypted += cipher.final('base64');
const result = Buffer.concat([salt, iv, Buffer.from(encrypted, 'base64')]).toString('base64');
return result;
}
function decrypt(encryptedText, password) {
const input = Buffer.from(encryptedText, 'base64');
const salt = input.slice(0, 16);
const iv = input.slice(16, 32);
const encrypted = input.slice(32);
const key = crypto.pbkdf2Sync(password, salt, 10000, 32, 'sha256');
const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
let decrypted = decipher.update(encrypted, 'base64', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
> encrypt('mysecrettext', 'mysecretkey')
'YRJnPLMis7e4Gj9mFDjwNPAPW6xn2EnsqRx/rcuUilLxJNbjKTC6g7HIoOaWCvZp'
> decrypt('YRJnPLMis7e4Gj9mFDjwNPAPW6xn2EnsqRx/rcuUilLxJNbjKTC6g7HIoOaWCvZp', 'mysecretkey')
'mysecrettext'
Encrypt/decrypt in Bash:
$ echo mysecrettext|openssl aes-256-cbc -a -A -salt -iter 10000 -pbkdf2 -k mysecretkey -e|b
ase64 -w0
VTJGc2RHVmtYMTl5c3NsY0s5azBMZ2wzK1ZocjNNeUhKM0d5Yll0aUtFVT0=
$(echo VTJGc2RHVmtYMTl5c3NsY0s5azBMZ2wzK1ZocjNNeUhKM0d5Yll0aUtFVT0=|base64 -d)|openssl aes-256-cbc -a -salt -iter 10000 -pbkdf2 -k mysecretkey -d
mysecrettext
But decrypting node’s output:
$ echo $(echo YRJnPLMis7e4Gj9mFDjwNPAPW6xn2EnsqRx/rcuUilLxJNbjKTC6g7HIoOaWCvZp|base64 -d)|openssl aes-256-cbc -a -salt -iter 10000 -pbkdf2 -k mysecretkey -d
error reading input file
What is missing for these methods to be able to decrypt each other’s data?
Tried to make sure the encryption/decryption methods and parameters in both environments are correct counterparts
bartv is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.