bitwiseshiftleft / sjcl

Stanford Javascript Crypto Library
http://bitwiseshiftleft.github.com/sjcl/
Other
7.18k stars 986 forks source link

Documentation says PKCS#5, but actually PKCS#7 padding is used. #417

Open ForestJohnson opened 4 years ago

ForestJohnson commented 4 years ago

Documentation says PKCS#5, but actually PKCS#7 padding is used.

Here: http://bitwiseshiftleft.github.io/sjcl/doc/sjcl.mode.cbc.html it says:

(static) encrypt(prp, plaintext, iv, adata)
Encrypt in CBC mode with PKCS#5 padding. 

But if you look in the code: http://bitwiseshiftleft.github.io/sjcl/doc/cbc.js.html#line42

First it constructs an integer that represents 4 padding bytes:

      /* Construct the pad. */
      bl = (16 - ((bl >> 3) & 15)) * 0x1010101;

Then it appends 4 copies of that integer for a total of 16 bytes to the end and then slices the array to grab the last bit of the plaintext plus the appropriate padding for the 16 byte block size of the cipher.

      /* Pad and encrypt. */
      iv = prp.encrypt(xor(iv,w.concat(plaintext,[bl,bl,bl,bl]).slice(i,i+4)));
      output.splice(i,0,iv[0],iv[1],iv[2],iv[3]);

PKCS#5 Padding is only defined for block sizes of 8 bytes. PKCS#7 is the same thing, just expanded for block sizes up to 256 bytes. For more information see: https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS#5_and_PKCS#7