Question

From node cryptos documentation:

"You can disable automatic padding of the input data to block size. If auto_padding is false, the length of the entire input data must be a multiple of the cipher's block size or final will fail. Useful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final."

Which is all nice, however, i wasn't able to find a proper example anywhere:

Here are my thoughts on the manner:

function pad(str) {
  if((str.length*8)%256 != 0) {
    str+= "0";
    pad(str);
  } 
}

var str = "blah_blah_blah_blah_ asdf";
if(byteLength < 256) {
  for(i=byteLength;i<256;i+=8) {
    str += "0";
  }
} else if(byteLength > 256) {
  pad(str);
}

Now this is obviously not ideal since the cipher.final() method should remove the padding, however it won't, also, i should probably pad it with hexes rather than chars.

Also, the modulus function fails on strings greater than 256 shrug

What's the proper way to use custom padding(0x0) with node crypto?

Was it helpful?

Solution

Ok, after a little bit of tinkering, i got the whole thing working.

Here's my code for those who might find it useful:

Updated for 2019 / node 10.15.0

node crypto will handle padding for you.

const crypto = require("crypto");
const iv = crypto.randomBytes(16);
let key = crypto.randomBytes(32);

function encrypt(str) {
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
    let crypt = cipher.update(str, 'utf8', 'base64');
    crypt += cipher.final("base64");
    return crypt;
}

function decrypt(str) {
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
    let decrypt = decipher.update(str, 'base64', 'utf8');
    decrypt += decipher.final();
    return decrypt;
}

const enc = encrypt("dude5");
const dec = decrypt(enc);

console.log(enc, dec);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top