Skip to content

Instantly share code, notes, and snippets.

@yingray
Created November 21, 2018 06:25
Show Gist options
  • Save yingray/f9b279163d21d9df268edf689ee2d262 to your computer and use it in GitHub Desktop.
Save yingray/f9b279163d21d9df268edf689ee2d262 to your computer and use it in GitHub Desktop.
Nodejs: aes-256-cbc examples (with iv, blockSize)
import crypto from "crypto";
const algorithm = "aes-256-cbc";
const Aes256 = (text, key, iv) => {
let cipher = crypto.createCipheriv(algorithm, new Buffer.from(key), new Buffer.from(iv));
cipher.setAutoPadding(false);
let encrypted = cipher.update(PKCS5Padding(text));
encrypted = Buffer.concat([encrypted]);
return encrypted.toString("hex");
};
function PKCS5Padding(string, blocksize = 16) {
const len = string.length;
const pad = blocksize - (len % blocksize);
const res = string + String.fromCharCode(pad).repeat(pad);
return res;
}
const plaintext = "abcdefghijklmnopqrstuvwxyzABCDEF"
const key = "12345678901234567890123456789012";
const iv = "1234567890123456"
const hashedText = Aes256(plaintext, key, iv)
console.log("Result: ", hashedText)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment