Skip to content

Commit

Permalink
Constant time code: improved implementations
Browse files Browse the repository at this point in the history
Change constant time code to be faster.
  • Loading branch information
SparkiDev committed Feb 26, 2025
1 parent 3557cc7 commit 4752bd2
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
29 changes: 19 additions & 10 deletions wolfcrypt/src/coding.c
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,25 @@ enum {
#ifdef BASE64_NO_TABLE
static WC_INLINE byte Base64_Char2Val(byte c)
{
word16 v = 0x0000;

v |= 0xff3E & ctMask16Eq(c, 0x2b);
v |= 0xff3F & ctMask16Eq(c, 0x2f);
v |= (c + 0xff04) & ctMask16GTE(c, 0x30) & ctMask16LTE(c, 0x39);
v |= (0xff00 + c - 0x41) & ctMask16GTE(c, 0x41) & ctMask16LTE(c, 0x5a);
v |= (0xff00 + c - 0x47) & ctMask16GTE(c, 0x61) & ctMask16LTE(c, 0x7a);
v |= ~(v >> 8);

return (byte)v;
word16 v;
sword16 smallEnd = (sword16)c - 0x7b;
sword16 smallStart = (sword16)c - 0x61;
sword16 bigEnd = (sword16)c - 0x5b;
sword16 bigStart = (sword16)c - 0x41;
sword16 numEnd = (sword16)c - 0x3a;
sword16 numStart = (sword16)c - 0x30;
sword16 slashEnd = (sword16)c - 0x30;
sword16 slashStart = (sword16)c - 0x2f;
sword16 plusEnd = (sword16)c - 0x2c;
sword16 plusStart = (sword16)c - 0x2b;

v = ((smallStart >> 8) ^ (smallEnd >> 8)) & (smallStart + 26 + 1);
v |= ((bigStart >> 8) ^ (bigEnd >> 8)) & (bigStart + 0 + 1);
v |= ((numStart >> 8) ^ (numEnd >> 8)) & (numStart + 52 + 1);
v |= ((slashStart >> 8) ^ (slashEnd >> 8)) & (slashStart + 63 + 1);
v |= ((plusStart >> 8) ^ (plusEnd >> 8)) & (plusStart + 62 + 1);

return (byte)(v - 1);
}
#else
static
Expand Down
14 changes: 12 additions & 2 deletions wolfcrypt/src/sp_int.c
Original file line number Diff line number Diff line change
Expand Up @@ -8027,8 +8027,18 @@ static void sp_clamp_ct(sp_int* a)
sp_size_t mask = (sp_size_t)-1;

for (i = (int)a->used - 1; i >= 0; i--) {
used = (sp_size_t)(used - ((a->dp[i] == 0) & mask));
mask &= (sp_size_t)(0 - (a->dp[i] == 0));
#if ((SP_WORD_SIZE == 64) && \
(defined(_WIN64) || !defined(WOLFSSL_UINT128_T_DEFINED))) || \
((SP_WORD_SIZE == 32) && defined(NO_64BIT))
sp_int_digit negVal = ~a->dp[i];
sp_int_digit minusOne = a->dp[i] - 1;
sp_int_digit zeroMask = (sp_int_sdigit)(negVal & minusOne) >>
(SP_WORD_SIZE - 1);
#else
sp_int_digit zeroMask = (((sp_int_sword)a->dp[i]) - 1) >> SP_WORD_SIZE;
#endif
mask &= (sp_size_t)zeroMask;
used = (sp_size_t)(used + mask);
}
a->used = used;
}
Expand Down

0 comments on commit 4752bd2

Please sign in to comment.