Skip to content

Instantly share code, notes, and snippets.

@marekgoczol
Created October 18, 2018 13:10
Show Gist options
  • Save marekgoczol/8c59cf481520fc26611a92ec78da3952 to your computer and use it in GitHub Desktop.
Save marekgoczol/8c59cf481520fc26611a92ec78da3952 to your computer and use it in GitHub Desktop.
// using https://github.com/ricmoo/aes-js
var key = aesjs.utils.utf8.toBytes('Bar12345Bar12345');
var iv = aesjs.utils.utf8.toBytes('RandomInitVector');
// encryption
var text = 'Hello W123123123123123123';
var textBytes = aesjs.padding.pkcs7.pad(aesjs.utils.utf8.toBytes(text));
var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
var encryptedBytes = aesCbc.encrypt(textBytes);
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(encryptedHex);
// decryption
var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);
// The cipher-block chaining mode of operation maintains internal
// state, so to decrypt a new instance must be instantiated.
var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
var decryptedBytes = aesjs.padding.pkcs7.strip(aesCbc.decrypt(encryptedBytes));
// Convert our bytes back into text
var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
console.log(decryptedText);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment