Created
November 21, 2018 06:25
-
-
Save yingray/f9b279163d21d9df268edf689ee2d262 to your computer and use it in GitHub Desktop.
Nodejs: aes-256-cbc examples (with iv, blockSize)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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