Last active
October 2, 2022 06:34
-
-
Save silicakes/9080839 to your computer and use it in GitHub Desktop.
NodeJS Crypto custom padding example
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
// 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"); |
thanks
thanks!
You're awesome! Thank you!
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?
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
thanks