Skip to content

Instantly share code, notes, and snippets.

@silicakes
Last active October 2, 2022 06:34
Show Gist options
  • Save silicakes/9080839 to your computer and use it in GitHub Desktop.
Save silicakes/9080839 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");
@fsck-mount
Copy link

Pass Key as well.

@gtsigner
Copy link

thanks

@chungguo
Copy link

chungguo commented Jun 3, 2019

thanks

@dusblinov
Copy link

thanks!

@qixuezheng
Copy link

You're awesome! Thank you!

@richlewis14
Copy link

richlewis14 commented Jun 23, 2021

Hey, thank you for posting this. Im facing an issue where my padding needs to be 0x0001 (KCS7Padding) on the decryption side, would this example work for this?

@silicakes
Copy link
Author

Hey, thank you for posting this. Im facing an issue where my padding needs to be 0x0001 (KCS7Padding) on the decryption side, would this example work for this?

It should, go ahead and try it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment