Skip to content

Commit 7c92fb2

Browse files
julek-wolfssldgarske
authored andcommitted
Use constant-time PKCS#7 padding check in EVP
F-763
1 parent fac0842 commit 7c92fb2

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

wolfcrypt/src/evp.c

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1263,13 +1263,17 @@ static int checkPad(WOLFSSL_EVP_CIPHER_CTX *ctx, unsigned char *buff)
12631263
{
12641264
int i;
12651265
int n;
1266+
byte mask = 0;
12661267
n = buff[ctx->block_size-1];
1267-
if (n > ctx->block_size || n == 0) return -1;
1268-
for (i = 0; i < n; i++) {
1269-
if (buff[ctx->block_size-i-1] != n)
1270-
return -1;
1271-
}
1272-
return ctx->block_size - n;
1268+
/* Encode invalid n into mask constant-time instead of early-returning,
1269+
* so the loop always runs and timing does not reveal padding length. */
1270+
mask |= ctMaskEq(n, 0) | ctMaskGT(n, ctx->block_size);
1271+
for (i = 0; i < ctx->block_size; i++) {
1272+
byte in_padding = ctMaskLT(i, n);
1273+
mask |= ctMaskSel(in_padding,
1274+
ctMaskNotEq(buff[ctx->block_size - 1 - i], n), 0);
1275+
}
1276+
return ctMaskSelInt(ctMaskEq(mask, 0), ctx->block_size - n, -1);
12731277
}
12741278

12751279
#if (defined(HAVE_AESGCM) || defined(HAVE_AESCCM) || \

0 commit comments

Comments
 (0)