Skip to content

Commit 9f06d33

Browse files
Merge pull request #6992 from SparkiDev/heapmath_addmod_ct
Heap math: mp_add/submod_ct make work when c == d
2 parents 008d495 + 416ce54 commit 9f06d33

1 file changed

Lines changed: 57 additions & 21 deletions

File tree

wolfcrypt/src/integer.c

Lines changed: 57 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3068,47 +3068,83 @@ int mp_submod(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
30683068
/* d = a + b (mod c) */
30693069
int mp_addmod(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
30703070
{
3071-
int res;
3072-
mp_int t;
3071+
int res;
3072+
mp_int t;
30733073

3074-
if ((res = mp_init (&t)) != MP_OKAY) {
3075-
return res;
3076-
}
3074+
if ((res = mp_init (&t)) != MP_OKAY) {
3075+
return res;
3076+
}
30773077

3078-
res = mp_add (a, b, &t);
3079-
if (res == MP_OKAY) {
3080-
res = mp_mod (&t, c, d);
3081-
}
3078+
res = mp_add (a, b, &t);
3079+
if (res == MP_OKAY) {
3080+
res = mp_mod (&t, c, d);
3081+
}
30823082

3083-
mp_clear (&t);
3083+
mp_clear (&t);
30843084

3085-
return res;
3085+
return res;
30863086
}
30873087

30883088
/* d = a - b (mod c) - a < c and b < c and positive */
30893089
int mp_submod_ct(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
30903090
{
3091-
int res;
3091+
int res;
3092+
mp_int t;
3093+
mp_int* r = d;
30923094

3093-
res = mp_sub(a, b, d);
3094-
if (res == MP_OKAY && mp_isneg(d)) {
3095-
res = mp_add(d, c, d);
3095+
if (c == d) {
3096+
r = &t;
3097+
3098+
if ((res = mp_init (r)) != MP_OKAY) {
3099+
return res;
30963100
}
3101+
}
30973102

3098-
return res;
3103+
res = mp_sub (a, b, r);
3104+
if (res == MP_OKAY) {
3105+
if (mp_isneg (r)) {
3106+
res = mp_add (r, c, d);
3107+
} else if (c == d) {
3108+
res = mp_copy (r, d);
3109+
}
3110+
}
3111+
3112+
if (c == d) {
3113+
mp_clear (r);
3114+
}
3115+
3116+
return res;
30993117
}
31003118

31013119
/* d = a + b (mod c) - a < c and b < c and positive */
31023120
int mp_addmod_ct(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
31033121
{
3104-
int res;
3122+
int res;
3123+
mp_int t;
3124+
mp_int* r = d;
3125+
3126+
if (c == d) {
3127+
r = &t;
31053128

3106-
res = mp_add(a, b, d);
3107-
if (res == MP_OKAY && mp_cmp(d, c) != MP_LT) {
3108-
res = mp_sub(d, c, d);
3129+
if ((res = mp_init (r)) != MP_OKAY) {
3130+
return res;
31093131
}
3132+
}
31103133

3111-
return res;
3134+
res = mp_add (a, b, r);
3135+
if (res == MP_OKAY) {
3136+
if (mp_cmp (r, c) != MP_LT) {
3137+
res = mp_sub (r, c, d);
3138+
} else if (c == d) {
3139+
res = mp_copy (r, d);
3140+
}
3141+
}
3142+
3143+
if (c == d) {
3144+
mp_clear (r);
3145+
}
3146+
3147+
return res;
31123148
}
31133149

31143150
/* computes b = a*a */

0 commit comments

Comments
 (0)