How to Encrypt / Decrypt with AES in Node.JS
Easy as pie!
var crypto = require('crypto');
var AES128 = "aes128";
var AES192 = "aes192";
var AES256 = "aes256";
var password = 'Austin';
var plainText = 'Texas to the bone!';
// ------------------------------------------------
var cipher = crypto.createCipher(AES128, password);
var decipher = crypto.createDecipher(AES128, password);
console.log('AES-128:');
// Encrypting with AES128
var encText = cipher.update(plainText, 'utf8', 'hex');
encText += cipher.final('hex');
console.log(encText);
// Decrypting with AES128
var decText = decipher.update(encText, 'hex', 'utf8');
decText += decipher.final('utf8');
console.log(decText);
console.log('\n');
// ------------------------------------------------
var cipher = crypto.createCipher(AES192, password);
var decipher = crypto.createDecipher(AES192, password);
console.log('AES-192:');
// Encrypting with AES192
var encText = cipher.update(plainText, 'utf8', 'hex');
encText += cipher.final('hex');
console.log(encText);
// Decrypting with AES192
var decText = decipher.update(encText, 'hex', 'utf8');
decText += decipher.final('utf8');
console.log(decText);
console.log('\n');
// ------------------------------------------------
var cipher = crypto.createCipher(AES256, password);
var decipher = crypto.createDecipher(AES256, password);
console.log('AES-256:');
// Encrypting with AES256
var encText = cipher.update(plainText, 'utf8', 'hex');
encText += cipher.final('hex');
console.log(encText);
// Decrypting with AES256
var decText = decipher.update(encText, 'hex', 'utf8');
decText += decipher.final('utf8');
console.log(decText);
console.log('\n');
You just copy all the obove code in some file with .js extension and run it!
The output should be similar to this:
E:\Codes\NodeJS\AES>node aesDemo.js
AES-128:
930022733c96373c2262ce9a6e4627bce4e4d103c4aeae95dfe7391a1e743de4
Texas to the bone!
AES-192:
fc6fe52653c7c6046c10e7162a5a7d3a1c4425ee38cc78dcd01e60e1431ed8c1
Texas to the bone!
AES-256:
4e09338018570c722f2184aecbfc317f850d11811ad8d0ca7a89df64d224998b
Texas to the bone!
I hope you find it useful.
Sources: