Skip to content

Instantly share code, notes, and snippets.

@akirattii
Last active August 21, 2018 03:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/39cb64d99ffb01334442739409c0a8d7 to your computer and use it in GitHub Desktop.
Save akirattii/39cb64d99ffb01334442739409c0a8d7 to your computer and use it in GitHub Desktop.
NodeJS: aes-encrypt / aes-decrypt by using string password. (Browser compatible and I think as a secure way at this point ...)
const aesjs = require('aes-js');
const pbkdf2 = require('pbkdf2');
const password = "mySecretPassword";
const message = "HelloWorld!";
const encrypted = encrypt(message, password);
console.log("encrypted:", encrypted); // 3ed20b7c474c96af513d1c
const decrypted = decrypt(encrypted, password);
console.log("decrypted:", decrypted); // HelloWorld!
function encrypt(msg, password, counter = 1) {
// Encrypt
const key = passwordToKey(password);
// Convert text to bytes
const textBytes = aesjs.utils.utf8.toBytes(msg);
// The counter is optional, and if omitted will begin at 1
const aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(counter));
const encryptedBytes = aesCtr.encrypt(textBytes);
// To print or store the binary data, you may convert it to hex
const encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
return encryptedHex;
}
function decrypt(encryptedHex, password, counter = 1) {
// Decrypt
// When ready to decrypt the hex string, convert it back to bytes
const encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);
const key = passwordToKey(password);
// The counter mode of operation maintains internal state, so to
// decrypt a new instance must be instantiated.
const aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(counter));
const decryptedBytes = aesCtr.decrypt(encryptedBytes);
// Convert our bytes back into text
const decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
return decryptedText;
}
function passwordToKey(password, salt, keyBits = 192) {
if (!salt) {
salt = password;
}
const key = pbkdf2.pbkdf2Sync(password, salt, 1, keyBits / 8, 'sha512'); // AES192
return key;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment