'use strict';
const crypto = require('crypto');
// get password's md5 hash
let password = 'test';
let password_hash = crypto.createHash('md5').update(password, 'utf-8').digest('hex').toUpperCase();
console.log('key=', password_hash); // 098F6BCD4621D373CADE4E832627B4F6
// our data to encrypt
let data = '06401;0001001;04;15650.05;03';
console.log('data=', data);
// generate initialization vector
let iv = new Buffer.alloc(16); // fill with zeros
console.log('iv=', iv);
// encrypt data
let cipher = crypto.createCipheriv('aes-256-cbc', password_hash, iv);
let encryptedData = cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
console.log('encrypted data=', encryptedData.toUpperCase());
Output:
key= 098F6BCD4621D373CADE4E832627B4F6
data= 06401;0001001;04;15650.05;03
iv= <Buffer 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00>
encrypted data= 67E5FA1AD27759C86EE86A86B9C97A7EAD12273A3DAAB5F408C5B04A1B979350
I'm encrypting my file on the command line using:
openssl aes-256-cbc -e -in test.env -out test.env.encrypted
and then trying to decrypt on node.js with:
But i'm getting the following error:
TypeError: Bad input string at Decipher.update (crypto.js:168:26) at decrypt (/Users/h/tmp/encrypt_test/test.coffee:10:18) at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:16:13) at Object.<anonymous> (/Users/h/tmp/encrypt_test/test.coffee:1:1) at Module._compile (module.js:569:30) at Object.CoffeeScript.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/index.js:63:23) at compileScript (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:265:29) at compilePath (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:220:14) at Object.exports.run (/usr/local/lib/node_modules/coffeescript/lib/coffeescript/command.js:141:20) at Object.<anonymous> (/usr/local/lib/node_modules/coffeescript/bin/coffee:15:45) at Module._compile (module.js:569:30) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:503:32) at tryModuleLoad (module.js:466:12) at Function.Module._load (module.js:458:3) at Function.Module.runMain (module.js:605:10) at startup (bootstrap_node.js:158:16) at bootstrap_node.js:575:3
Any ideas?