Skip to content

Commit 9fc7e42

Browse files
authored
Merge pull request wolfSSL#8507 from SparkiDev/ct_fixes_3
Constant time code: improved implementations
2 parents a073868 + 4752bd2 commit 9fc7e42

File tree

2 files changed

+31
-12
lines changed

2 files changed

+31
-12
lines changed

wolfcrypt/src/coding.c

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -62,16 +62,25 @@ enum {
6262
#ifdef BASE64_NO_TABLE
6363
static WC_INLINE byte Base64_Char2Val(byte c)
6464
{
65-
word16 v = 0x0000;
66-
67-
v |= 0xff3E & ctMask16Eq(c, 0x2b);
68-
v |= 0xff3F & ctMask16Eq(c, 0x2f);
69-
v |= (c + 0xff04) & ctMask16GTE(c, 0x30) & ctMask16LTE(c, 0x39);
70-
v |= (0xff00 + c - 0x41) & ctMask16GTE(c, 0x41) & ctMask16LTE(c, 0x5a);
71-
v |= (0xff00 + c - 0x47) & ctMask16GTE(c, 0x61) & ctMask16LTE(c, 0x7a);
72-
v |= ~(v >> 8);
73-
74-
return (byte)v;
65+
word16 v;
66+
sword16 smallEnd = (sword16)c - 0x7b;
67+
sword16 smallStart = (sword16)c - 0x61;
68+
sword16 bigEnd = (sword16)c - 0x5b;
69+
sword16 bigStart = (sword16)c - 0x41;
70+
sword16 numEnd = (sword16)c - 0x3a;
71+
sword16 numStart = (sword16)c - 0x30;
72+
sword16 slashEnd = (sword16)c - 0x30;
73+
sword16 slashStart = (sword16)c - 0x2f;
74+
sword16 plusEnd = (sword16)c - 0x2c;
75+
sword16 plusStart = (sword16)c - 0x2b;
76+
77+
v = ((smallStart >> 8) ^ (smallEnd >> 8)) & (smallStart + 26 + 1);
78+
v |= ((bigStart >> 8) ^ (bigEnd >> 8)) & (bigStart + 0 + 1);
79+
v |= ((numStart >> 8) ^ (numEnd >> 8)) & (numStart + 52 + 1);
80+
v |= ((slashStart >> 8) ^ (slashEnd >> 8)) & (slashStart + 63 + 1);
81+
v |= ((plusStart >> 8) ^ (plusEnd >> 8)) & (plusStart + 62 + 1);
82+
83+
return (byte)(v - 1);
7584
}
7685
#else
7786
static

wolfcrypt/src/sp_int.c

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8020,8 +8020,18 @@ static void sp_clamp_ct(sp_int* a)
80208020
sp_size_t mask = (sp_size_t)-1;
80218021

80228022
for (i = (int)a->used - 1; i >= 0; i--) {
8023-
used = (sp_size_t)(used - ((a->dp[i] == 0) & mask));
8024-
mask &= (sp_size_t)(0 - (a->dp[i] == 0));
8023+
#if ((SP_WORD_SIZE == 64) && \
8024+
(defined(_WIN64) || !defined(WOLFSSL_UINT128_T_DEFINED))) || \
8025+
((SP_WORD_SIZE == 32) && defined(NO_64BIT))
8026+
sp_int_digit negVal = ~a->dp[i];
8027+
sp_int_digit minusOne = a->dp[i] - 1;
8028+
sp_int_digit zeroMask = (sp_int_sdigit)(negVal & minusOne) >>
8029+
(SP_WORD_SIZE - 1);
8030+
#else
8031+
sp_int_digit zeroMask = (((sp_int_sword)a->dp[i]) - 1) >> SP_WORD_SIZE;
8032+
#endif
8033+
mask &= (sp_size_t)zeroMask;
8034+
used = (sp_size_t)(used + mask);
80258035
}
80268036
a->used = used;
80278037
}

0 commit comments

Comments
 (0)