Non constant time padding check in SunJCE PKCS5Padding

Bernd Eckenfels ecki at zusammenkunft.net
Tue May 10 22:01:30 UTC 2016


Hello,

I had a look at the PKCS5Padding because I had the problem that
AES/CBC/NOPADDING is much faster than AES/CBC/PKCS5PADDING (for larger
single block with doFinal() encryptions). I havent found out the reason
for that (I suspect it does a unecesary input copy). (opening another
thread for this)

But whhat I have seen is that the unpad() method does a non
constant-time compare of the padding.

I guess it cant be entirely avoided that the padding check tells
anything about the cleartext (and EtM schemes are there for a reason).

But I still think the final "are all padding bytes correct" can be
changed into a xor comparision with no early return:

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/com/sun/crypto/provider/PKCS5Padding.java/
108       for (int i = 0; i < ((int)lastByte & 0x0ff); i++) {
109            if (in[start+i] != lastByte) {
110                return -1;
111            }
112        }

use this:

int difference = 0;
for(int i = 0; i < ((int)astByte & 0xff); i++) {
  difference |= in[start+1] ^ lastByte;
}
return difference == 0?start:-1;

This would be minor (preventive) security hardening.

Gruss
Bernd



More information about the security-dev mailing list