Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Constant time code: improved implementations #8507

Merged
merged 1 commit into from
Mar 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading