encrypt message with AES-CBC with PKCS#7 padding using forge.js

2k views Asked by At

I need to apply PKCS#7 padding to data which is being digested with AES-CBC algorithm. I use forge lib. Here's my currently working code (without the padding):

// transform json data to bytes
var data = {foo: 'bar'};
var stringData = JSON.stringify(data);
var bytes = forge.util.createBuffer(stringData);

// generate 16-byte vector iv
var iv = forge.random.getBytesSync(16);

// ciphering process
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(bytes);
cipher.finish();
var encrypted = cipher.output;

So from the theoretical point of view I know that I should append 1-16 bytes to my bytes variable before passing it to aes algorithm. Is this kind of operation built into the forge lib? If not, could someone help me with implementing application of padding to the message?

1

There are 1 answers

0
pedrofb On BEST ANSWER

Althought the documentation does not mention it, seems the default padding for AES-CBC is PKCS#7. See this thread and the comments of cipherModes.js

modes.cbc.prototype.pad = function(input, options) {
  // add PKCS#7 padding to block (each pad byte is the
  // value of the number of pad bytes)