Skip to content

Instantly share code, notes, and snippets.

@bang9
Forked from silicakes/nodeJSCustomPadding.js
Created July 28, 2020 01:08
Show Gist options
  • Save bang9/2d202eb8dea397737253f36161a596fb to your computer and use it in GitHub Desktop.
Save bang9/2d202eb8dea397737253f36161a596fb to your computer and use it in GitHub Desktop.
NodeJS Crypto custom padding example
// Following an answer I posted to my question here:
// http://stackoverflow.com/questions/21856892/node-crypto-aes256-cbc-0x0-padding-example/21858749#21858749
//I'm expecting a utf8 encoded string
function customPadding(str, blockSize, padder, format) {
str = new Buffer(str,"utf8").toString(format);
//1 char = 8bytes
var bitLength = str.length*8;
if(bitLength < blockSize) {
for(i=bitLength;i<blockSize;i+=8) {
str += padder;
}
} else if(bitLength > blockSize) {
while((str.length*8)%blockSize != 0) {
str+= padder;
}
}
return new Buffer(str, format).toString("utf8");
}
function encrypt(str) {
var cipher = crypto.createCipheriv('aes-256-cbc', key, iv).setAutoPadding(false);
str = customPadding(str, 256, 0x0, "hex"); // magic happens here
var crypt = cipher.update(str, 'utf8', 'base64');
crypt += cipher.final("base64");
return crypt;
}
var t = encrypt("dude");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment