Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save chusri/22a3c37eb00f88ec88e5f8573d44430d to your computer and use it in GitHub Desktop.
Save chusri/22a3c37eb00f88ec88e5f8573d44430d to your computer and use it in GitHub Desktop.
AES-256-CBC example in Node.js using crypto module

AES-256-CBC example in Node.js using crypto module

'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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment