Coverage Report

Created: 2026-07-22 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-heapmath/wolfcrypt/src/integer.c
Line
Count
Source
1
/* integer.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
/*
25
 * Based on public domain LibTomMath 0.38 by Tom St Denis, tomstdenis@iahu.ca,
26
 * http://math.libtomcrypt.com
27
 */
28
29
#ifndef NO_BIG_INT
30
31
#if !defined(USE_FAST_MATH) && defined(USE_INTEGER_HEAP_MATH)
32
33
#ifndef WOLFSSL_SP_MATH
34
35
#ifdef NO_INLINE
36
    #include <wolfssl/wolfcrypt/misc.h>
37
#else
38
    #define WOLFSSL_MISC_INCLUDED
39
    #include <wolfcrypt/src/misc.c>
40
#endif
41
42
#include <wolfssl/wolfcrypt/wolfmath.h>
43
44
#if defined(FREESCALE_LTC_TFM)
45
    #include <wolfssl/wolfcrypt/port/nxp/ksdk_port.h>
46
#endif
47
#ifdef WOLFSSL_DEBUG_MATH
48
    #include <stdio.h>
49
#endif
50
51
#ifdef SHOW_GEN
52
    #ifndef NO_STDIO_FILESYSTEM
53
        #include <stdio.h>
54
    #endif
55
#endif
56
57
#if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH)
58
#ifdef __cplusplus
59
    extern "C" {
60
#endif
61
WOLFSSL_LOCAL int sp_ModExp_1024(mp_int* base, mp_int* exp, mp_int* mod,
62
    mp_int* res);
63
WOLFSSL_LOCAL int sp_ModExp_1536(mp_int* base, mp_int* exp, mp_int* mod,
64
    mp_int* res);
65
WOLFSSL_LOCAL int sp_ModExp_2048(mp_int* base, mp_int* exp, mp_int* mod,
66
    mp_int* res);
67
WOLFSSL_LOCAL int sp_ModExp_3072(mp_int* base, mp_int* exp, mp_int* mod,
68
    mp_int* res);
69
WOLFSSL_LOCAL int sp_ModExp_4096(mp_int* base, mp_int* exp, mp_int* mod,
70
    mp_int* res);
71
#ifdef __cplusplus
72
    } /* extern "C" */
73
#endif
74
#endif
75
76
/* reverse an array, used for radix code */
77
static void
78
bn_reverse (unsigned char *s, int len)
79
0
{
80
0
    int     ix, iy;
81
0
    unsigned char t;
82
83
0
    ix = 0;
84
0
    iy = len - 1;
85
0
    while (ix < iy) {
86
0
        t     = s[ix];
87
0
        s[ix] = s[iy];
88
0
        s[iy] = t;
89
0
        ++ix;
90
0
        --iy;
91
0
    }
92
0
}
93
94
/* math settings check */
95
word32 CheckRunTimeSettings(void)
96
0
{
97
0
    return CTC_SETTINGS;
98
0
}
99
100
101
/* handle up to 6 inits */
102
int mp_init_multi(mp_int* a, mp_int* b, mp_int* c, mp_int* d, mp_int* e,
103
                  mp_int* f)
104
0
{
105
0
    int res = MP_OKAY;
106
107
0
    if (a) XMEMSET(a, 0, sizeof(mp_int));
108
0
    if (b) XMEMSET(b, 0, sizeof(mp_int));
109
0
    if (c) XMEMSET(c, 0, sizeof(mp_int));
110
0
    if (d) XMEMSET(d, 0, sizeof(mp_int));
111
0
    if (e) XMEMSET(e, 0, sizeof(mp_int));
112
0
    if (f) XMEMSET(f, 0, sizeof(mp_int));
113
114
0
    if (a && ((res = mp_init(a)) != MP_OKAY))
115
0
        return res;
116
117
0
    if (b && ((res = mp_init(b)) != MP_OKAY)) {
118
0
        mp_clear(a);
119
0
        return res;
120
0
    }
121
122
0
    if (c && ((res = mp_init(c)) != MP_OKAY)) {
123
0
        mp_clear(a); mp_clear(b);
124
0
        return res;
125
0
    }
126
127
0
    if (d && ((res = mp_init(d)) != MP_OKAY)) {
128
0
        mp_clear(a); mp_clear(b); mp_clear(c);
129
0
        return res;
130
0
    }
131
132
0
    if (e && ((res = mp_init(e)) != MP_OKAY)) {
133
0
        mp_clear(a); mp_clear(b); mp_clear(c); mp_clear(d);
134
0
        return res;
135
0
    }
136
137
0
    if (f && ((res = mp_init(f)) != MP_OKAY)) {
138
0
        mp_clear(a); mp_clear(b); mp_clear(c); mp_clear(d); mp_clear(e);
139
0
        return res;
140
0
    }
141
142
0
    return res;
143
0
}
144
145
146
/* init a new mp_int */
147
int mp_init (mp_int * a)
148
0
{
149
  /* Safeguard against passing in a null pointer */
150
0
  if (a == NULL)
151
0
    return MP_VAL;
152
153
  /* defer allocation until mp_grow */
154
0
  a->dp = NULL;
155
156
  /* set the used to zero, allocated digits to the default precision
157
   * and sign to positive */
158
0
  a->used  = 0;
159
0
  a->alloc = 0;
160
0
  a->sign  = MP_ZPOS;
161
#ifdef HAVE_WOLF_BIGINT
162
  wc_bigint_init(&a->raw);
163
#endif
164
165
0
  return MP_OKAY;
166
0
}
167
168
169
/* clear one (frees)  */
170
void mp_clear (mp_int * a)
171
0
{
172
#ifdef HAVE_FIPS
173
    mp_forcezero(a);
174
#else
175
0
  int i;
176
177
0
  if (a == NULL)
178
0
      return;
179
180
  /* only do anything if a hasn't been freed previously */
181
0
#ifndef HAVE_WOLF_BIGINT
182
  /* When HAVE_WOLF_BIGINT then mp_free -> wc_bigint_free needs to be called
183
   * because a->raw->buf may be allocated even when a->dp == NULL. This is the
184
   * case for when a zero is loaded into the mp_int. */
185
0
  if (a->dp != NULL)
186
0
#endif
187
0
  {
188
    /* first zero the digits */
189
0
    for (i = 0; i < a->used; i++) {
190
0
        a->dp[i] = 0;
191
0
    }
192
193
    /* free ram */
194
0
    mp_free(a);
195
196
    /* reset members to make debugging easier */
197
0
    a->alloc = a->used = 0;
198
0
    a->sign  = MP_ZPOS;
199
0
  }
200
0
#endif
201
0
}
202
203
void mp_free (mp_int * a)
204
0
{
205
  /* only do anything if a hasn't been freed previously */
206
0
  if (a->dp != NULL) {
207
    /* free ram */
208
0
    XFREE(a->dp, 0, DYNAMIC_TYPE_BIGINT);
209
0
    a->dp    = NULL;
210
0
  }
211
212
#ifdef HAVE_WOLF_BIGINT
213
  wc_bigint_free(&a->raw);
214
#endif
215
0
}
216
217
void mp_forcezero(mp_int * a)
218
0
{
219
0
    if (a == NULL)
220
0
        return;
221
222
    /* only do anything if a hasn't been freed previously */
223
0
    if (a->dp != NULL) {
224
      /* force zero the used digits */
225
0
      ForceZero(a->dp, a->used * sizeof(mp_digit));
226
#ifdef HAVE_WOLF_BIGINT
227
      wc_bigint_zero(&a->raw);
228
#endif
229
      /* free ram */
230
0
      mp_free(a);
231
232
      /* reset members to make debugging easier */
233
0
      a->alloc = a->used = 0;
234
0
      a->sign  = MP_ZPOS;
235
0
    }
236
237
0
    a->sign = MP_ZPOS;
238
0
    a->used = 0;
239
0
}
240
241
242
/* get the size for an unsigned equivalent */
243
int mp_unsigned_bin_size (const mp_int * a)
244
0
{
245
0
  int     size = mp_count_bits (a);
246
0
  return (size / 8 + ((size & 7) != 0 ? 1 : 0));
247
0
}
248
249
250
/* returns the number of bits in an int */
251
int mp_count_bits (const mp_int * a)
252
0
{
253
0
  int     r;
254
0
  mp_digit q;
255
256
  /* shortcut */
257
0
  if (a->used == 0) {
258
0
    return 0;
259
0
  }
260
261
  /* get number of digits and add that */
262
0
  r = (a->used - 1) * DIGIT_BIT;
263
264
  /* take the last digit and count the bits in it */
265
0
  q = a->dp[a->used - 1];
266
0
  while (q > ((mp_digit) 0)) {
267
0
    ++r;
268
0
    q >>= ((mp_digit) 1);
269
0
  }
270
0
  return r;
271
0
}
272
273
274
int mp_leading_bit (mp_int * a)
275
0
{
276
0
    int c = mp_count_bits(a);
277
278
0
    if (c == 0) return 0;
279
0
    return (c % 8) == 0;
280
0
}
281
282
int mp_to_unsigned_bin_at_pos(int x, mp_int *t, unsigned char *b)
283
0
{
284
0
  int res = 0;
285
0
  while (mp_iszero(t) == MP_NO) {
286
0
#ifndef MP_8BIT
287
0
      b[x++] = (unsigned char) (t->dp[0] & 255);
288
#else
289
      b[x++] = (unsigned char) (t->dp[0] | ((t->dp[1] & 0x01) << 7));
290
#endif
291
0
    if ((res = mp_div_2d (t, 8, t, NULL)) != MP_OKAY) {
292
0
      return res;
293
0
    }
294
0
    res = x;
295
0
  }
296
0
  return res;
297
0
}
298
299
/* store in unsigned [big endian] format */
300
int mp_to_unsigned_bin (const mp_int * a, unsigned char *b)
301
0
{
302
0
  int     x, res;
303
0
  mp_int  t;
304
305
0
  if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
306
0
    return res;
307
0
  }
308
309
0
  x = mp_to_unsigned_bin_at_pos(0, &t, b);
310
0
  if (x < 0) {
311
0
    mp_clear(&t);
312
0
    return x;
313
0
  }
314
315
0
  bn_reverse (b, x);
316
0
  mp_clear (&t);
317
0
  return res;
318
0
}
319
320
int mp_to_unsigned_bin_len(mp_int * a, unsigned char *b, int c)
321
0
{
322
0
    int i, len;
323
324
0
    len = mp_unsigned_bin_size(a);
325
326
0
    if (len > c) {
327
0
      return MP_VAL;
328
0
    }
329
330
    /* pad front w/ zeros to match length */
331
0
    for (i = 0; i < c - len; i++) {
332
0
      b[i] = 0x00;
333
0
    }
334
0
    return mp_to_unsigned_bin(a, b + i);
335
0
}
336
337
/* creates "a" then copies b into it */
338
int mp_init_copy (mp_int * a, const mp_int * b)
339
0
{
340
0
  int     res;
341
342
0
  if ((res = mp_init_size (a, b->used)) != MP_OKAY) {
343
0
    return res;
344
0
  }
345
346
0
  if((res = mp_copy (b, a)) != MP_OKAY) {
347
0
    mp_clear(a);
348
0
  }
349
350
0
  return res;
351
0
}
352
353
354
/* copy, b = a */
355
int mp_copy (const mp_int * a, mp_int * b)
356
0
{
357
0
  int     res, n;
358
359
  /* Safeguard against passing in a null pointer */
360
0
  if (a == NULL || b == NULL)
361
0
    return MP_VAL;
362
363
  /* if dst == src do nothing */
364
0
  if (a == b) {
365
0
    return MP_OKAY;
366
0
  }
367
368
  /* grow dest */
369
0
  if (b->alloc < a->used || b->alloc == 0) {
370
0
     if ((res = mp_grow (b, a->used)) != MP_OKAY) {
371
0
        return res;
372
0
     }
373
0
  }
374
375
  /* zero b and copy the parameters over */
376
0
  {
377
0
    mp_digit *tmpa, *tmpb;
378
379
    /* pointer aliases */
380
381
    /* source */
382
0
    tmpa = a->dp;
383
384
    /* destination */
385
0
    tmpb = b->dp;
386
387
    /* copy all the digits */
388
0
    for (n = 0; n < a->used; n++) {
389
0
      *tmpb++ = *tmpa++;
390
0
    }
391
392
    /* clear high digits */
393
0
    for (; n < b->used && b->dp; n++) {
394
0
      *tmpb++ = 0;
395
0
    }
396
0
  }
397
398
  /* copy used count and sign */
399
0
  b->used = a->used;
400
0
  b->sign = a->sign;
401
0
  return MP_OKAY;
402
0
}
403
404
405
/* grow as required */
406
int mp_grow (mp_int * a, int size)
407
0
{
408
0
  mp_digit *tmp;
409
410
  /* if the alloc size is smaller alloc more ram */
411
0
  if ((a->alloc < size) || (size == 0) || (a->alloc == 0)) {
412
    /* ensure there are always at least MP_PREC digits extra on top */
413
0
    size += (MP_PREC * 2) - (size % MP_PREC);
414
415
    /* reallocate the array a->dp
416
     *
417
     * We store the return in a temporary variable
418
     * in case the operation failed we don't want
419
     * to overwrite the dp member of a.
420
     */
421
0
    tmp = (mp_digit *)XREALLOC (a->dp, sizeof (mp_digit) * size, NULL,
422
0
                                                           DYNAMIC_TYPE_BIGINT);
423
0
    if (tmp == NULL) {
424
      /* reallocation failed but "a" is still valid [can be freed] */
425
0
      return MP_MEM;
426
0
    }
427
428
    /* reallocation succeeded so set a->dp */
429
0
    a->dp = tmp;
430
431
    /* zero excess digits */
432
0
    XMEMSET(&a->dp[a->alloc], 0, sizeof (mp_digit) * (size - a->alloc));
433
0
    a->alloc = size;
434
0
  }
435
0
  else if (a->dp == NULL) {
436
      /* opportunistic sanity check for null a->dp with nonzero a->alloc */
437
0
      return MP_VAL;
438
0
  }
439
0
  return MP_OKAY;
440
0
}
441
442
443
/* shift right by a certain bit count (store quotient in c, optional
444
   remainder in d) */
445
int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
446
0
{
447
0
  int     D, res;
448
0
  mp_int  t;
449
450
451
  /* if the shift count is <= 0 then we do no work */
452
0
  if (b <= 0) {
453
0
    res = mp_copy (a, c);
454
0
    if (d != NULL) {
455
0
      mp_zero (d);
456
0
    }
457
0
    return res;
458
0
  }
459
460
0
  if ((res = mp_init (&t)) != MP_OKAY) {
461
0
    return res;
462
0
  }
463
464
  /* get the remainder */
465
0
  if (d != NULL) {
466
0
    if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
467
0
      mp_clear (&t);
468
0
      return res;
469
0
    }
470
0
  }
471
472
  /* copy */
473
0
  if ((res = mp_copy (a, c)) != MP_OKAY) {
474
0
    mp_clear (&t);
475
0
    return res;
476
0
  }
477
478
  /* shift by as many digits in the bit count */
479
0
  if (b >= (int)DIGIT_BIT) {
480
0
    mp_rshd (c, b / DIGIT_BIT);
481
0
  }
482
483
  /* shift any bit count < DIGIT_BIT */
484
0
  D = (b % DIGIT_BIT);
485
0
  if (D != 0) {
486
0
    mp_rshb(c, D);
487
0
  }
488
0
  mp_clamp (c);
489
0
  if (d != NULL) {
490
0
    mp_exch (&t, d);
491
0
  }
492
0
  mp_clear (&t);
493
0
  return MP_OKAY;
494
0
}
495
496
497
/* set to zero */
498
void mp_zero (mp_int * a)
499
0
{
500
0
  int       n;
501
0
  mp_digit *tmp;
502
503
0
  if (a == NULL)
504
0
      return;
505
506
0
  a->sign = MP_ZPOS;
507
0
  a->used = 0;
508
509
0
  tmp = a->dp;
510
0
  for (n = 0; tmp != NULL && n < a->alloc; n++) {
511
0
     *tmp++ = 0;
512
0
  }
513
0
}
514
515
516
/* trim unused digits
517
 *
518
 * This is used to ensure that leading zero digits are
519
 * trimmed and the leading "used" digit will be non-zero
520
 * Typically very fast.  Also fixes the sign if there
521
 * are no more leading digits
522
 */
523
void mp_clamp (mp_int * a)
524
0
{
525
  /* decrease used while the most significant digit is
526
   * zero.
527
   */
528
0
  while (a->used > 0 && a->dp[a->used - 1] == 0) {
529
0
    --(a->used);
530
0
  }
531
532
  /* reset the sign flag if used == 0 */
533
0
  if (a->used == 0) {
534
0
    a->sign = MP_ZPOS;
535
0
  }
536
0
}
537
538
539
/* swap the elements of two integers, for cases where you can't simply swap the
540
 * mp_int pointers around
541
 */
542
int mp_exch (mp_int * a, mp_int * b)
543
0
{
544
0
  mp_int  t;
545
546
0
  t  = *a;
547
0
  *a = *b;
548
0
  *b = t;
549
0
  return MP_OKAY;
550
0
}
551
552
/* Constant-time conditional swap: must not branch on m (leaks scalar bit).
553
 * m must be 0 or 1. The t parameter is unused; XOR is performed in place
554
 * with a single-digit stack scratch so callers don't need to clear t->dp. */
555
int mp_cond_swap_ct_ex (mp_int * a, mp_int * b, int c, int m, mp_int * t)
556
0
{
557
0
    int i;
558
0
    int err;
559
0
    int imask;
560
0
    int idiff;
561
0
    mp_digit mask;
562
0
    mp_digit d;
563
564
0
    (void)t;
565
566
0
    m &= 1;
567
0
    imask = -m;
568
0
    mask = (mp_digit)0 - (mp_digit)m;
569
570
0
    if ((err = mp_grow(a, c)) != MP_OKAY)
571
0
        return err;
572
0
    if ((err = mp_grow(b, c)) != MP_OKAY)
573
0
        return err;
574
575
0
    idiff = (a->used ^ b->used) & imask;
576
0
    a->used ^= idiff;
577
0
    b->used ^= idiff;
578
0
    idiff = (a->sign ^ b->sign) & imask;
579
0
    a->sign ^= idiff;
580
0
    b->sign ^= idiff;
581
582
0
    for (i = 0; i < c; i++) {
583
0
        d = (a->dp[i] ^ b->dp[i]) & mask;
584
0
        a->dp[i] ^= d;
585
0
        b->dp[i] ^= d;
586
0
    }
587
588
0
    return MP_OKAY;
589
0
}
590
591
int mp_cond_swap_ct (mp_int * a, mp_int * b, int c, int m)
592
0
{
593
0
    return mp_cond_swap_ct_ex(a, b, c, m, NULL);
594
0
}
595
596
597
/* shift right a certain number of bits */
598
void mp_rshb (mp_int *c, int x)
599
0
{
600
0
    mp_digit *tmpc, mask, shift;
601
0
    mp_digit r, rr;
602
0
    mp_digit D = x;
603
604
    /* shifting by a negative number not supported, and shifting by
605
     * zero changes nothing.
606
     */
607
0
    if (x <= 0) return;
608
609
    /* shift digits first if needed */
610
0
    if (x >= DIGIT_BIT) {
611
0
        mp_rshd(c, x / DIGIT_BIT);
612
        /* recalculate number of bits to shift */
613
0
        D = x % DIGIT_BIT;
614
        /* check if any more shifting needed */
615
0
        if (D == 0) return;
616
0
    }
617
618
    /* zero shifted is always zero */
619
0
    if (mp_iszero(c)) return;
620
621
    /* mask */
622
0
    mask = (((mp_digit)1) << D) - 1;
623
624
    /* shift for lsb */
625
0
    shift = DIGIT_BIT - D;
626
627
    /* alias */
628
0
    tmpc = c->dp + (c->used - 1);
629
630
    /* carry */
631
0
    r = 0;
632
0
    for (x = c->used - 1; x >= 0; x--) {
633
      /* get the lower  bits of this word in a temp */
634
0
      rr = *tmpc & mask;
635
636
      /* shift the current word and mix in the carry bits from previous word */
637
0
      *tmpc = (*tmpc >> D) | (r << shift);
638
0
      --tmpc;
639
640
      /* set the carry to the carry bits of the current word found above */
641
0
      r = rr;
642
0
    }
643
0
    mp_clamp(c);
644
0
}
645
646
647
/* shift right a certain amount of digits */
648
void mp_rshd (mp_int * a, int b)
649
0
{
650
0
  int     x;
651
652
  /* if b <= 0 then ignore it */
653
0
  if (b <= 0) {
654
0
    return;
655
0
  }
656
657
  /* if b > used then simply zero it and return */
658
0
  if (a->used <= b) {
659
0
    mp_zero (a);
660
0
    return;
661
0
  }
662
663
0
  {
664
0
    mp_digit *bottom, *top;
665
666
    /* shift the digits down */
667
668
    /* bottom */
669
0
    bottom = a->dp;
670
671
    /* top [offset into digits] */
672
0
    top = a->dp + b;
673
674
    /* this is implemented as a sliding window where
675
     * the window is b-digits long and digits from
676
     * the top of the window are copied to the bottom
677
     *
678
     * e.g.
679
680
     b-2 | b-1 | b0 | b1 | b2 | ... | bb |   ---->
681
                 /\                   |      ---->
682
                  \-------------------/      ---->
683
     */
684
0
    for (x = 0; x < (a->used - b); x++) {
685
0
      *bottom++ = *top++;
686
0
    }
687
688
    /* zero the top digits */
689
0
    for (; x < a->used; x++) {
690
0
      *bottom++ = 0;
691
0
    }
692
0
  }
693
694
  /* remove excess digits */
695
0
  a->used -= b;
696
0
}
697
698
699
/* calc a value mod 2**b */
700
int mp_mod_2d (mp_int * a, int b, mp_int * c)
701
0
{
702
0
  int     x, res, bmax;
703
704
  /* if b is <= 0 then zero the int */
705
0
  if (b <= 0) {
706
0
    mp_zero (c);
707
0
    return MP_OKAY;
708
0
  }
709
710
  /* if the modulus is larger than the value than return */
711
0
  if (a->sign == MP_ZPOS && b >= (int) (a->used * DIGIT_BIT)) {
712
0
    res = mp_copy (a, c);
713
0
    return res;
714
0
  }
715
716
  /* copy */
717
0
  if ((res = mp_copy (a, c)) != MP_OKAY) {
718
0
    return res;
719
0
  }
720
721
  /* calculate number of digits in mod value */
722
0
  bmax = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1);
723
  /* zero digits above the last digit of the modulus */
724
0
  for (x = bmax; x < c->used; x++) {
725
0
    c->dp[x] = 0;
726
0
  }
727
728
0
  if (c->sign == MP_NEG) {
729
0
     mp_digit carry = 0;
730
731
     /* grow result to size of modulus */
732
0
     if ((res = mp_grow(c, bmax)) != MP_OKAY) {
733
0
         return res;
734
0
     }
735
     /* negate value */
736
0
     for (x = 0; x < c->used; x++) {
737
0
         mp_digit next = c->dp[x] > 0;
738
0
         c->dp[x] = ((mp_digit)0 - c->dp[x] - carry) & MP_MASK;
739
0
         carry |= next;
740
0
     }
741
0
     for (; x < bmax; x++) {
742
0
         c->dp[x] = ((mp_digit)0 - carry) & MP_MASK;
743
0
     }
744
0
     c->used = bmax;
745
0
     c->sign = MP_ZPOS;
746
0
  }
747
748
  /* clear the digit that is not completely outside/inside the modulus */
749
0
  x = DIGIT_BIT - (b % DIGIT_BIT);
750
0
  if (x != DIGIT_BIT) {
751
0
    c->dp[bmax - 1] &=
752
0
         ((mp_digit)~((mp_digit)0)) >> (x + ((sizeof(mp_digit)*8) - DIGIT_BIT));
753
0
  }
754
0
  mp_clamp (c);
755
0
  return MP_OKAY;
756
0
}
757
758
759
/* reads a unsigned char array, assumes the msb is stored first [big endian] */
760
int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
761
0
{
762
0
  int     res;
763
0
  int     digits_needed;
764
765
0
  if (c < 0) {
766
0
      return MP_VAL;
767
0
  }
768
769
0
  while (c > 0 && b[0] == 0) {
770
0
      c--;
771
0
      b++;
772
0
  }
773
774
  /* reject sizes where the bit count would overflow, doing the math in
775
   * word32 so c * CHAR_BIT can't overflow */
776
0
  if ((word32)c > (WOLFSSL_MAX_32BIT - (DIGIT_BIT - 1)) / CHAR_BIT) {
777
0
      return MP_VAL;
778
0
  }
779
780
0
  digits_needed = (int)(((word32)c * CHAR_BIT + DIGIT_BIT - 1) / DIGIT_BIT);
781
782
  /* make sure there are enough digits available */
783
0
  if (a->alloc < digits_needed) {
784
0
     if ((res = mp_grow(a, digits_needed)) != MP_OKAY) {
785
0
        return res;
786
0
     }
787
0
  }
788
789
  /* zero the int */
790
0
  mp_zero (a);
791
792
  /* read the bytes in */
793
0
  while (c-- > 0) {
794
0
    if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) {
795
0
      return res;
796
0
    }
797
798
0
#ifndef MP_8BIT
799
0
      a->dp[0] |= *b++;
800
0
      if (a->used == 0)
801
0
          a->used = 1;
802
#else
803
      a->dp[0] = (*b & MP_MASK);
804
      a->dp[1] |= ((*b++ >> 7U) & 1);
805
      if (a->used == 0)
806
          a->used = 2;
807
#endif
808
0
  }
809
0
  mp_clamp (a);
810
0
  return MP_OKAY;
811
0
}
812
813
814
/* shift left by a certain bit count */
815
int mp_mul_2d (mp_int * a, int b, mp_int * c)
816
0
{
817
0
  mp_digit d;
818
0
  int      res;
819
820
  /* copy */
821
0
  if (a != c) {
822
0
     if ((res = mp_copy (a, c)) != MP_OKAY) {
823
0
       return res;
824
0
     }
825
0
  }
826
827
0
  if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) {
828
0
     if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) {
829
0
       return res;
830
0
     }
831
0
  }
832
833
  /* shift by as many digits in the bit count */
834
0
  if (b >= (int)DIGIT_BIT) {
835
0
    if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) {
836
0
      return res;
837
0
    }
838
0
  }
839
840
  /* shift any bit count < DIGIT_BIT */
841
0
  d = (mp_digit) (b % DIGIT_BIT);
842
0
  if (d != 0) {
843
0
    mp_digit *tmpc, shift, mask, r, rr;
844
0
    int x;
845
846
    /* bitmask for carries */
847
0
    mask = (((mp_digit)1) << d) - 1;
848
849
    /* shift for msbs */
850
0
    shift = DIGIT_BIT - d;
851
852
    /* alias */
853
0
    tmpc = c->dp;
854
855
    /* carry */
856
0
    r    = 0;
857
0
    for (x = 0; x < c->used; x++) {
858
      /* get the higher bits of the current word */
859
0
      rr = (*tmpc >> shift) & mask;
860
861
      /* shift the current word and OR in the carry */
862
0
      *tmpc = (mp_digit)(((*tmpc << d) | r) & MP_MASK);
863
0
      ++tmpc;
864
865
      /* set the carry to the carry bits of the current word */
866
0
      r = rr;
867
0
    }
868
869
    /* set final carry */
870
0
    if (r != 0) {
871
0
       c->dp[(c->used)++] = r;
872
0
    }
873
0
  }
874
0
  mp_clamp (c);
875
0
  return MP_OKAY;
876
0
}
877
878
879
/* shift left a certain amount of digits */
880
int mp_lshd (mp_int * a, int b)
881
0
{
882
0
  int     x, res;
883
884
  /* if its less than zero return */
885
0
  if (b <= 0) {
886
0
    return MP_OKAY;
887
0
  }
888
889
  /* grow to fit the new digits */
890
0
  if (a->alloc < a->used + b) {
891
0
     if ((res = mp_grow (a, a->used + b)) != MP_OKAY) {
892
0
       return res;
893
0
     }
894
0
  }
895
896
0
  {
897
0
    mp_digit *top, *bottom;
898
899
    /* increment the used by the shift amount then copy upwards */
900
0
    a->used += b;
901
902
    /* top */
903
0
    top = a->dp + a->used - 1;
904
905
    /* base */
906
0
    bottom = a->dp + a->used - 1 - b;
907
908
    /* much like mp_rshd this is implemented using a sliding window
909
     * except the window goes the other way around.  Copying from
910
     * the bottom to the top.  see bn_mp_rshd.c for more info.
911
     */
912
0
    for (x = a->used - 1; x >= b; x--) {
913
0
      *top-- = *bottom--;
914
0
    }
915
916
    /* zero the lower digits */
917
0
    top = a->dp;
918
0
    for (x = 0; x < b; x++) {
919
0
      *top++ = 0;
920
0
    }
921
0
  }
922
0
  return MP_OKAY;
923
0
}
924
925
926
/* this is a shell function that calls either the normal or Montgomery
927
 * exptmod functions.  Originally the call to the montgomery code was
928
 * embedded in the normal function but that wasted a lot of stack space
929
 * for nothing (since 99% of the time the Montgomery code would be called)
930
 */
931
#if defined(FREESCALE_LTC_TFM)
932
int wolfcrypt_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
933
#else
934
    int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y) /* //NOLINT(misc-no-recursion) */
935
#endif
936
0
{
937
0
  int dr;
938
939
  /* modulus P must be positive */
940
0
  if (mp_iszero(P) || P->sign == MP_NEG) {
941
0
     return MP_VAL;
942
0
  }
943
0
  if (mp_isone(P)) {
944
0
     return mp_set(Y, 0);
945
0
  }
946
0
  if (mp_iszero(X)) {
947
0
     return mp_set(Y, 1);
948
0
  }
949
0
  if (mp_iszero(G)) {
950
0
     return mp_set(Y, 0);
951
0
  }
952
953
  /* if exponent X is negative we have to recurse */
954
0
  if (X->sign == MP_NEG) {
955
0
#ifdef BN_MP_INVMOD_C
956
0
     mp_int tmpG, tmpX;
957
0
     int err;
958
959
     /* first compute 1/G mod P */
960
0
     if ((err = mp_init(&tmpG)) != MP_OKAY) {
961
0
        return err;
962
0
     }
963
0
     if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
964
0
        mp_clear(&tmpG);
965
0
        return err;
966
0
     }
967
968
     /* now get |X| */
969
0
     if ((err = mp_init(&tmpX)) != MP_OKAY) {
970
0
        mp_clear(&tmpG);
971
0
        return err;
972
0
     }
973
0
     if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
974
0
        mp_clear(&tmpG);
975
0
        mp_clear(&tmpX);
976
0
        return err;
977
0
     }
978
979
     /* and now compute (1/G)**|X| instead of G**X [X < 0] */
980
0
     err = mp_exptmod(&tmpG, &tmpX, P, Y);
981
0
     mp_clear(&tmpG);
982
0
     mp_clear(&tmpX);
983
0
     return err;
984
#else
985
     /* no invmod */
986
     return MP_VAL;
987
#endif
988
0
  }
989
990
0
#ifdef BN_MP_EXPTMOD_BASE_2
991
0
  if (G->used == 1 && G->dp[0] == 2 && mp_isodd(P) == MP_YES) {
992
0
    return mp_exptmod_base_2(X, P, Y);
993
0
  }
994
0
#endif
995
996
/* modified diminished radix reduction */
997
0
#if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && \
998
0
  defined(BN_S_MP_EXPTMOD_C)
999
0
  if (mp_reduce_is_2k_l(P) == MP_YES) {
1000
0
     return s_mp_exptmod(G, X, P, Y, 1);
1001
0
  }
1002
0
#endif
1003
1004
0
#ifdef BN_MP_DR_IS_MODULUS_C
1005
  /* is it a DR modulus? */
1006
0
  dr = mp_dr_is_modulus(P);
1007
#else
1008
  /* default to no */
1009
  dr = 0;
1010
#endif
1011
1012
0
  (void)dr;
1013
1014
0
#ifdef BN_MP_REDUCE_IS_2K_C
1015
  /* if not, is it a unrestricted DR modulus? */
1016
0
  if (dr == 0) {
1017
0
     dr = mp_reduce_is_2k(P) << 1;
1018
0
  }
1019
0
#endif
1020
1021
  /* if the modulus is odd use the montgomery method, or use other known */
1022
0
#ifdef BN_MP_EXPTMOD_FAST_C
1023
0
  if (mp_isodd (P) == MP_YES || dr !=  0) {
1024
0
    return mp_exptmod_fast (G, X, P, Y, dr);
1025
0
  } else {
1026
0
#endif
1027
0
#ifdef BN_S_MP_EXPTMOD_C
1028
    /* otherwise use the generic Barrett reduction technique */
1029
0
    return s_mp_exptmod (G, X, P, Y, 0);
1030
#else
1031
    /* no exptmod for evens */
1032
    return MP_VAL;
1033
#endif
1034
0
#ifdef BN_MP_EXPTMOD_FAST_C
1035
0
  }
1036
0
#endif
1037
0
}
1038
1039
int mp_exptmod_ex (mp_int * G, mp_int * X, int digits, mp_int * P, mp_int * Y)
1040
0
{
1041
0
    (void)digits;
1042
0
    return mp_exptmod(G, X, P, Y);
1043
0
}
1044
1045
/* b = |a|
1046
 *
1047
 * Simple function copies the input and fixes the sign to positive
1048
 */
1049
int mp_abs (mp_int * a, mp_int * b)
1050
0
{
1051
0
  int     res;
1052
1053
  /* copy a to b */
1054
0
  if (a != b) {
1055
0
     if ((res = mp_copy (a, b)) != MP_OKAY) {
1056
0
       return res;
1057
0
     }
1058
0
  }
1059
1060
  /* force the sign of b to positive */
1061
0
  b->sign = MP_ZPOS;
1062
1063
0
  return MP_OKAY;
1064
0
}
1065
1066
1067
/* hac 14.61, pp608 */
1068
#if defined(FREESCALE_LTC_TFM)
1069
int wolfcrypt_mp_invmod(mp_int * a, mp_int * b, mp_int * c)
1070
#else
1071
int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
1072
#endif
1073
0
{
1074
  /* b cannot be negative or zero, and can not divide by 0 (1/a mod b) */
1075
0
  if (b->sign == MP_NEG || mp_iszero(b) == MP_YES || mp_iszero(a) == MP_YES) {
1076
0
    return MP_VAL;
1077
0
  }
1078
1079
0
#ifdef BN_FAST_MP_INVMOD_C
1080
  /* if the modulus is odd we can use a faster routine instead */
1081
0
  if ((mp_isodd(b) == MP_YES) && (mp_cmp_d(b, 1) != MP_EQ)) {
1082
0
    return fast_mp_invmod (a, b, c);
1083
0
  }
1084
0
#endif
1085
1086
0
#ifdef BN_MP_INVMOD_SLOW_C
1087
0
  return mp_invmod_slow(a, b, c);
1088
#else
1089
  return MP_VAL;
1090
#endif
1091
0
}
1092
1093
1094
/* computes the modular inverse via binary extended euclidean algorithm,
1095
 * that is c = 1/a mod b
1096
 *
1097
 * Based on slow invmod except this is optimized for the case where b is
1098
 * odd as per HAC Note 14.64 on pp. 610
1099
 */
1100
int fast_mp_invmod (mp_int * a, mp_int * b, mp_int * c)
1101
0
{
1102
0
  mp_int  x, y, u, v, B, D;
1103
0
  int     res, loop_check = 0;
1104
1105
  /* 2. [modified] b must be odd   */
1106
0
  if (mp_iseven (b) == MP_YES) {
1107
0
    return MP_VAL;
1108
0
  }
1109
1110
  /* init all our temps */
1111
0
  if ((res = mp_init_multi(&x, &y, &u, &v, &B, &D)) != MP_OKAY) {
1112
0
     return res;
1113
0
  }
1114
1115
  /* x == modulus, y == value to invert */
1116
0
  if ((res = mp_copy (b, &x)) != MP_OKAY) {
1117
0
    goto LBL_ERR;
1118
0
  }
1119
1120
  /* we need y = |a| */
1121
0
  if ((res = mp_mod (a, b, &y)) != MP_OKAY) {
1122
0
    goto LBL_ERR;
1123
0
  }
1124
1125
0
  if (mp_iszero (&y) == MP_YES) {
1126
    /* invmod doesn't exist for this a and b */
1127
0
    res = MP_VAL;
1128
0
    goto LBL_ERR;
1129
0
  }
1130
1131
  /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
1132
0
  if ((res = mp_copy (&x, &u)) != MP_OKAY) {
1133
0
    goto LBL_ERR;
1134
0
  }
1135
0
  if ((res = mp_copy (&y, &v)) != MP_OKAY) {
1136
0
    goto LBL_ERR;
1137
0
  }
1138
0
  if ((res = mp_set (&D, 1)) != MP_OKAY) {
1139
0
    goto LBL_ERR;
1140
0
  }
1141
1142
0
top:
1143
  /* 4.  while u is even do */
1144
0
  while (mp_iseven (&u) == MP_YES) {
1145
    /* 4.1 u = u/2 */
1146
0
    if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
1147
0
      goto LBL_ERR;
1148
0
    }
1149
    /* 4.2 if B is odd then */
1150
0
    if (mp_isodd (&B) == MP_YES) {
1151
0
      if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
1152
0
        goto LBL_ERR;
1153
0
      }
1154
0
    }
1155
    /* B = B/2 */
1156
0
    if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
1157
0
      goto LBL_ERR;
1158
0
    }
1159
0
  }
1160
1161
  /* 5.  while v is even do */
1162
0
  while (mp_iseven (&v) == MP_YES) {
1163
    /* 5.1 v = v/2 */
1164
0
    if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
1165
0
      goto LBL_ERR;
1166
0
    }
1167
    /* 5.2 if D is odd then */
1168
0
    if (mp_isodd (&D) == MP_YES) {
1169
      /* D = (D-x)/2 */
1170
0
      if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
1171
0
        goto LBL_ERR;
1172
0
      }
1173
0
    }
1174
    /* D = D/2 */
1175
0
    if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
1176
0
      goto LBL_ERR;
1177
0
    }
1178
0
  }
1179
1180
  /* 6.  if u >= v then */
1181
0
  if (mp_cmp (&u, &v) != MP_LT) {
1182
    /* u = u - v, B = B - D */
1183
0
    if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
1184
0
      goto LBL_ERR;
1185
0
    }
1186
1187
0
    if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
1188
0
      goto LBL_ERR;
1189
0
    }
1190
0
  } else {
1191
    /* v - v - u, D = D - B */
1192
0
    if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
1193
0
      goto LBL_ERR;
1194
0
    }
1195
1196
0
    if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
1197
0
      goto LBL_ERR;
1198
0
    }
1199
0
  }
1200
1201
  /* if not zero goto step 4 */
1202
0
  if (mp_iszero (&u) == MP_NO) {
1203
0
    if (++loop_check > MAX_INVMOD_SZ) {
1204
0
        res = MP_VAL;
1205
0
        goto LBL_ERR;
1206
0
    }
1207
0
    goto top;
1208
0
  }
1209
1210
  /* now a = C, b = D, gcd == g*v */
1211
1212
  /* if v != 1 then there is no inverse */
1213
0
  if (mp_cmp_d (&v, 1) != MP_EQ) {
1214
0
    res = MP_VAL;
1215
0
    goto LBL_ERR;
1216
0
  }
1217
1218
  /* b is now the inverse */
1219
0
  while (D.sign == MP_NEG) {
1220
0
    if ((res = mp_add (&D, b, &D)) != MP_OKAY) {
1221
0
      goto LBL_ERR;
1222
0
    }
1223
0
  }
1224
  /* too big */
1225
0
  while (mp_cmp_mag(&D, b) != MP_LT) {
1226
0
      if ((res = mp_sub(&D, b, &D)) != MP_OKAY) {
1227
0
         goto LBL_ERR;
1228
0
      }
1229
0
  }
1230
0
  mp_exch (&D, c);
1231
0
  res = MP_OKAY;
1232
1233
0
LBL_ERR:mp_clear(&x);
1234
0
        mp_clear(&y);
1235
0
        mp_clear(&u);
1236
0
        mp_clear(&v);
1237
0
        mp_clear(&B);
1238
0
        mp_clear(&D);
1239
0
  return res;
1240
0
}
1241
1242
1243
/* hac 14.61, pp608 */
1244
int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c)
1245
0
{
1246
0
  mp_int  x, y, u, v, A, B, C, D;
1247
0
  int     res;
1248
1249
  /* b cannot be negative */
1250
0
  if (b->sign == MP_NEG || mp_iszero(b) == MP_YES) {
1251
0
    return MP_VAL;
1252
0
  }
1253
1254
  /* init temps */
1255
0
  if ((res = mp_init_multi(&x, &y, &u, &v,
1256
0
                           &A, &B)) != MP_OKAY) {
1257
0
    return res;
1258
0
  }
1259
1260
  /* init rest of tmps temps */
1261
0
  if ((res = mp_init_multi(&C, &D, 0, 0, 0, 0)) != MP_OKAY) {
1262
0
    mp_clear(&x);
1263
0
    mp_clear(&y);
1264
0
    mp_clear(&u);
1265
0
    mp_clear(&v);
1266
0
    mp_clear(&A);
1267
0
    mp_clear(&B);
1268
0
    return res;
1269
0
  }
1270
1271
  /* x = a, y = b */
1272
0
  if ((res = mp_mod(a, b, &x)) != MP_OKAY) {
1273
0
    goto LBL_ERR;
1274
0
  }
1275
1276
0
  if (mp_iszero (&x) == MP_YES) {
1277
    /* invmod doesn't exist for this a and b */
1278
0
    res = MP_VAL;
1279
0
    goto LBL_ERR;
1280
0
  }
1281
1282
0
  if (mp_isone(&x)) {
1283
0
    res = mp_set(c, 1);
1284
0
    goto LBL_ERR;
1285
0
  }
1286
0
  if ((res = mp_copy (b, &y)) != MP_OKAY) {
1287
0
    goto LBL_ERR;
1288
0
  }
1289
1290
  /* 2. [modified] if x,y are both even then return an error! */
1291
0
  if (mp_iseven (&x) == MP_YES && mp_iseven (&y) == MP_YES) {
1292
0
    res = MP_VAL;
1293
0
    goto LBL_ERR;
1294
0
  }
1295
1296
  /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
1297
0
  if ((res = mp_copy (&x, &u)) != MP_OKAY) {
1298
0
    goto LBL_ERR;
1299
0
  }
1300
0
  if ((res = mp_copy (&y, &v)) != MP_OKAY) {
1301
0
    goto LBL_ERR;
1302
0
  }
1303
0
  if ((res = mp_set (&A, 1)) != MP_OKAY) {
1304
0
    goto LBL_ERR;
1305
0
  }
1306
0
  if ((res = mp_set (&D, 1)) != MP_OKAY) {
1307
0
    goto LBL_ERR;
1308
0
  }
1309
1310
0
top:
1311
  /* 4.  while u is even do */
1312
0
  while (mp_iseven (&u) == MP_YES) {
1313
    /* 4.1 u = u/2 */
1314
0
    if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
1315
0
      goto LBL_ERR;
1316
0
    }
1317
    /* 4.2 if A or B is odd then */
1318
0
    if (mp_isodd (&A) == MP_YES || mp_isodd (&B) == MP_YES) {
1319
      /* A = (A+y)/2, B = (B-x)/2 */
1320
0
      if ((res = mp_add (&A, &y, &A)) != MP_OKAY) {
1321
0
        goto LBL_ERR;
1322
0
      }
1323
0
      if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
1324
0
        goto LBL_ERR;
1325
0
      }
1326
0
    }
1327
    /* A = A/2, B = B/2 */
1328
0
    if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
1329
0
      goto LBL_ERR;
1330
0
    }
1331
0
    if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
1332
0
      goto LBL_ERR;
1333
0
    }
1334
0
  }
1335
1336
  /* 5.  while v is even do */
1337
0
  while (mp_iseven (&v) == MP_YES) {
1338
    /* 5.1 v = v/2 */
1339
0
    if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
1340
0
      goto LBL_ERR;
1341
0
    }
1342
    /* 5.2 if C or D is odd then */
1343
0
    if (mp_isodd (&C) == MP_YES || mp_isodd (&D) == MP_YES) {
1344
      /* C = (C+y)/2, D = (D-x)/2 */
1345
0
      if ((res = mp_add (&C, &y, &C)) != MP_OKAY) {
1346
0
        goto LBL_ERR;
1347
0
      }
1348
0
      if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
1349
0
        goto LBL_ERR;
1350
0
      }
1351
0
    }
1352
    /* C = C/2, D = D/2 */
1353
0
    if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
1354
0
      goto LBL_ERR;
1355
0
    }
1356
0
    if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
1357
0
      goto LBL_ERR;
1358
0
    }
1359
0
  }
1360
1361
  /* 6.  if u >= v then */
1362
0
  if (mp_cmp (&u, &v) != MP_LT) {
1363
    /* u = u - v, A = A - C, B = B - D */
1364
0
    if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
1365
0
      goto LBL_ERR;
1366
0
    }
1367
1368
0
    if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
1369
0
      goto LBL_ERR;
1370
0
    }
1371
1372
0
    if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
1373
0
      goto LBL_ERR;
1374
0
    }
1375
0
  } else {
1376
    /* v - v - u, C = C - A, D = D - B */
1377
0
    if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
1378
0
      goto LBL_ERR;
1379
0
    }
1380
1381
0
    if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
1382
0
      goto LBL_ERR;
1383
0
    }
1384
1385
0
    if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
1386
0
      goto LBL_ERR;
1387
0
    }
1388
0
  }
1389
1390
  /* if not zero goto step 4 */
1391
0
  if (mp_iszero (&u) == MP_NO)
1392
0
    goto top;
1393
1394
  /* now a = C, b = D, gcd == g*v */
1395
1396
  /* if v != 1 then there is no inverse */
1397
0
  if (mp_cmp_d (&v, 1) != MP_EQ) {
1398
0
    res = MP_VAL;
1399
0
    goto LBL_ERR;
1400
0
  }
1401
1402
  /* if its too low */
1403
0
  while (mp_cmp_d(&C, 0) == MP_LT) {
1404
0
      if ((res = mp_add(&C, b, &C)) != MP_OKAY) {
1405
0
         goto LBL_ERR;
1406
0
      }
1407
0
  }
1408
1409
  /* too big */
1410
0
  while (mp_cmp_mag(&C, b) != MP_LT) {
1411
0
      if ((res = mp_sub(&C, b, &C)) != MP_OKAY) {
1412
0
         goto LBL_ERR;
1413
0
      }
1414
0
  }
1415
1416
  /* C is now the inverse */
1417
0
  mp_exch (&C, c);
1418
0
  res = MP_OKAY;
1419
0
LBL_ERR:mp_clear(&x);
1420
0
        mp_clear(&y);
1421
0
        mp_clear(&u);
1422
0
        mp_clear(&v);
1423
0
        mp_clear(&A);
1424
0
        mp_clear(&B);
1425
0
        mp_clear(&C);
1426
0
        mp_clear(&D);
1427
0
  return res;
1428
0
}
1429
1430
1431
/* compare magnitude of two ints (unsigned) */
1432
int mp_cmp_mag (const mp_int * a, const mp_int * b)
1433
0
{
1434
0
  int     n;
1435
0
  const mp_digit *tmpa, *tmpb;
1436
1437
  /* compare based on # of non-zero digits */
1438
0
  if (a->used > b->used) {
1439
0
    return MP_GT;
1440
0
  }
1441
1442
0
  if (a->used < b->used) {
1443
0
    return MP_LT;
1444
0
  }
1445
1446
0
  if (a->used == 0)
1447
0
      return MP_EQ;
1448
1449
  /* alias for a */
1450
0
  tmpa = a->dp + (a->used - 1);
1451
1452
  /* alias for b */
1453
0
  tmpb = b->dp + (a->used - 1);
1454
1455
  /* compare based on digits  */
1456
0
  for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
1457
0
    if (*tmpa > *tmpb) {
1458
0
      return MP_GT;
1459
0
    }
1460
1461
0
    if (*tmpa < *tmpb) {
1462
0
      return MP_LT;
1463
0
    }
1464
0
  }
1465
0
  return MP_EQ;
1466
0
}
1467
1468
1469
/* compare two ints (signed)*/
1470
int mp_cmp (const mp_int * a, const mp_int * b)
1471
0
{
1472
  /* compare based on sign */
1473
0
  if (a->sign != b->sign) {
1474
0
     if (a->sign == MP_NEG) {
1475
0
        return MP_LT;
1476
0
     } else {
1477
0
        return MP_GT;
1478
0
     }
1479
0
  }
1480
1481
  /* compare digits */
1482
0
  if (a->sign == MP_NEG) {
1483
     /* if negative compare opposite direction */
1484
0
     return mp_cmp_mag(b, a);
1485
0
  } else {
1486
0
     return mp_cmp_mag(a, b);
1487
0
  }
1488
0
}
1489
1490
1491
/* compare a digit */
1492
int mp_cmp_d(mp_int * a, mp_digit b)
1493
0
{
1494
  /* special case for zero*/
1495
0
  if (a->used == 0 && b == 0)
1496
0
    return MP_EQ;
1497
1498
  /* compare based on sign */
1499
0
  if ((b && a->used == 0) || a->sign == MP_NEG) {
1500
0
    return MP_LT;
1501
0
  }
1502
1503
  /* compare based on magnitude */
1504
0
  if (a->used > 1) {
1505
0
    return MP_GT;
1506
0
  }
1507
1508
  /* compare the only digit of a to b */
1509
0
  if (a->dp[0] > b) {
1510
0
    return MP_GT;
1511
0
  } else if (a->dp[0] < b) {
1512
0
    return MP_LT;
1513
0
  } else {
1514
0
    return MP_EQ;
1515
0
  }
1516
0
}
1517
1518
1519
/* set to a digit */
1520
int mp_set (mp_int * a, mp_digit b)
1521
0
{
1522
0
  int res;
1523
0
  mp_zero (a);
1524
0
  res = mp_grow (a, 1);
1525
0
  if (res == MP_OKAY) {
1526
0
    a->dp[0] = (mp_digit)(b & MP_MASK);
1527
0
    a->used  = (a->dp[0] != 0) ? 1 : 0;
1528
0
  }
1529
0
  return res;
1530
0
}
1531
1532
/* check if a bit is set */
1533
int mp_is_bit_set (mp_int *a, mp_digit b)
1534
0
{
1535
0
    mp_digit i = b / DIGIT_BIT;  /* word index */
1536
0
    mp_digit s = b % DIGIT_BIT;  /* bit index */
1537
1538
0
    if ((mp_digit)a->used <= i) {
1539
        /* no words available at that bit count */
1540
0
        return 0;
1541
0
    }
1542
1543
    /* get word and shift bit to check down to index 0 */
1544
0
    return (int)((a->dp[i] >> s) & (mp_digit)1);
1545
0
}
1546
1547
/* c = a mod b, 0 <= c < b */
1548
#if defined(FREESCALE_LTC_TFM)
1549
int wolfcrypt_mp_mod(mp_int * a, mp_int * b, mp_int * c)
1550
#else
1551
int mp_mod (mp_int * a, mp_int * b, mp_int * c)
1552
#endif
1553
0
{
1554
0
  mp_int  t;
1555
0
  int     res;
1556
1557
0
  if ((res = mp_init_size (&t, b->used)) != MP_OKAY) {
1558
0
    return res;
1559
0
  }
1560
1561
0
  if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) {
1562
0
    mp_clear (&t);
1563
0
    return res;
1564
0
  }
1565
1566
0
  if ((mp_iszero(&t) != MP_NO) || (t.sign == b->sign)) {
1567
0
    res = MP_OKAY;
1568
0
    mp_exch (&t, c);
1569
0
  } else {
1570
0
    res = mp_add (b, &t, c);
1571
0
  }
1572
1573
0
  mp_clear (&t);
1574
0
  return res;
1575
0
}
1576
1577
1578
/* slower bit-bang division... also smaller */
1579
int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d)
1580
0
{
1581
0
   mp_int ta, tb, tq, q;
1582
0
   int    res, n, n2;
1583
1584
  /* is divisor zero ? */
1585
0
  if (mp_iszero (b) == MP_YES) {
1586
0
    return MP_VAL;
1587
0
  }
1588
1589
  /* if a < b then q=0, r = a */
1590
0
  if (mp_cmp_mag (a, b) == MP_LT) {
1591
0
    if (d != NULL) {
1592
0
      res = mp_copy (a, d);
1593
0
    } else {
1594
0
      res = MP_OKAY;
1595
0
    }
1596
0
    if (c != NULL) {
1597
0
      mp_zero (c);
1598
0
    }
1599
0
    return res;
1600
0
  }
1601
1602
  /* init our temps */
1603
0
  if ((res = mp_init_multi(&ta, &tb, &tq, &q, 0, 0)) != MP_OKAY) {
1604
0
     return res;
1605
0
  }
1606
1607
0
  if ((res = mp_set(&tq, 1)) != MP_OKAY) {
1608
0
     return res;
1609
0
  }
1610
0
  n = mp_count_bits(a) - mp_count_bits(b);
1611
0
  if (((res = mp_abs(a, &ta)) != MP_OKAY) ||
1612
0
      ((res = mp_abs(b, &tb)) != MP_OKAY) ||
1613
0
      ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) ||
1614
0
      ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) {
1615
0
      goto LBL_ERR;
1616
0
  }
1617
1618
0
  while (n-- >= 0) {
1619
0
     if (mp_cmp(&tb, &ta) != MP_GT) {
1620
0
        if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) ||
1621
0
            ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) {
1622
0
           goto LBL_ERR;
1623
0
        }
1624
0
     }
1625
0
     if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) ||
1626
0
         ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) {
1627
0
           goto LBL_ERR;
1628
0
     }
1629
0
  }
1630
1631
  /* now q == quotient and ta == remainder */
1632
0
  n  = a->sign;
1633
0
  n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG);
1634
0
  if (c != NULL) {
1635
0
     mp_exch(c, &q);
1636
0
     c->sign  = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2;
1637
0
  }
1638
0
  if (d != NULL) {
1639
0
     mp_exch(d, &ta);
1640
0
     d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n;
1641
0
  }
1642
0
LBL_ERR:
1643
0
   mp_clear(&ta);
1644
0
   mp_clear(&tb);
1645
0
   mp_clear(&tq);
1646
0
   mp_clear(&q);
1647
0
   return res;
1648
0
}
1649
1650
1651
/* b = a/2 */
1652
int mp_div_2(mp_int * a, mp_int * b)
1653
0
{
1654
0
  int     x, res, oldused;
1655
1656
  /* copy */
1657
0
  if (b->alloc < a->used) {
1658
0
    if ((res = mp_grow (b, a->used)) != MP_OKAY) {
1659
0
      return res;
1660
0
    }
1661
0
  }
1662
1663
0
  oldused = b->used;
1664
0
  b->used = a->used;
1665
0
  {
1666
0
    mp_digit r, rr, *tmpa, *tmpb;
1667
1668
    /* source alias */
1669
0
    tmpa = a->dp + b->used - 1;
1670
1671
    /* dest alias */
1672
0
    tmpb = b->dp + b->used - 1;
1673
1674
    /* carry */
1675
0
    r = 0;
1676
0
    for (x = b->used - 1; x >= 0; x--) {
1677
      /* get the carry for the next iteration */
1678
0
      rr = *tmpa & 1;
1679
1680
      /* shift the current digit, add in carry and store */
1681
0
      *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
1682
1683
      /* forward carry to next iteration */
1684
0
      r = rr;
1685
0
    }
1686
1687
    /* zero excess digits */
1688
0
    tmpb = b->dp + b->used;
1689
0
    for (x = b->used; x < oldused; x++) {
1690
0
      *tmpb++ = 0;
1691
0
    }
1692
0
  }
1693
0
  b->sign = a->sign;
1694
0
  mp_clamp (b);
1695
0
  return MP_OKAY;
1696
0
}
1697
1698
/* c = a / 2 (mod b) - constant time (a < b and positive) */
1699
int mp_div_2_mod_ct(mp_int *a, mp_int *b, mp_int *c)
1700
0
{
1701
0
    int res;
1702
1703
0
    if (mp_isodd(a)) {
1704
0
        res = mp_add(a, b, c);
1705
0
        if (res == MP_OKAY) {
1706
0
            res = mp_div_2(c, c);
1707
0
        }
1708
0
    }
1709
0
    else {
1710
0
        res = mp_div_2(a, c);
1711
0
    }
1712
1713
0
    return res;
1714
0
}
1715
1716
1717
/* high level addition (handles signs) */
1718
int mp_add (mp_int * a, mp_int * b, mp_int * c)
1719
0
{
1720
0
  int sa, sb, res;
1721
1722
  /* get sign of both inputs */
1723
0
  sa = a->sign;
1724
0
  sb = b->sign;
1725
1726
  /* handle two cases, not four */
1727
0
  if (sa == sb) {
1728
    /* both positive or both negative */
1729
    /* add their magnitudes, copy the sign */
1730
0
    c->sign = sa;
1731
0
    res = s_mp_add (a, b, c);
1732
0
  } else {
1733
    /* one positive, the other negative */
1734
    /* subtract the one with the greater magnitude from */
1735
    /* the one of the lesser magnitude.  The result gets */
1736
    /* the sign of the one with the greater magnitude. */
1737
0
    if (mp_cmp_mag (a, b) == MP_LT) {
1738
0
      c->sign = sb;
1739
0
      res = s_mp_sub (b, a, c);
1740
0
    } else {
1741
0
      c->sign = sa;
1742
0
      res = s_mp_sub (a, b, c);
1743
0
    }
1744
0
  }
1745
0
  return res;
1746
0
}
1747
1748
1749
/* low level addition, based on HAC pp.594, Algorithm 14.7 */
1750
int s_mp_add (mp_int * a, mp_int * b, mp_int * c)
1751
0
{
1752
0
  mp_int *x;
1753
0
  int     olduse, res, min_ab, max_ab;
1754
1755
  /* find sizes, we let |a| <= |b| which means we have to sort
1756
   * them.  "x" will point to the input with the most digits
1757
   */
1758
0
  if (a->used > b->used) {
1759
0
    min_ab = b->used;
1760
0
    max_ab = a->used;
1761
0
    x = a;
1762
0
  } else {
1763
0
    min_ab = a->used;
1764
0
    max_ab = b->used;
1765
0
    x = b;
1766
0
  }
1767
1768
  /* init result */
1769
0
  if (c->dp == NULL || c->alloc < max_ab + 1) {
1770
0
    if ((res = mp_grow (c, max_ab + 1)) != MP_OKAY) {
1771
0
      return res;
1772
0
    }
1773
0
  }
1774
1775
  /* get old used digit count and set new one */
1776
0
  olduse = c->used;
1777
0
  c->used = max_ab + 1;
1778
1779
0
  {
1780
0
    mp_digit u, *tmpa, *tmpb, *tmpc;
1781
0
    int i;
1782
1783
    /* alias for digit pointers */
1784
1785
    /* first input */
1786
0
    tmpa = a->dp;
1787
1788
    /* second input */
1789
0
    tmpb = b->dp;
1790
1791
    /* destination */
1792
0
    tmpc = c->dp;
1793
1794
    /* sanity-check dp pointers. */
1795
0
    if ((min_ab > 0) &&
1796
0
        ((tmpa == NULL) || (tmpb == NULL) || (tmpc == NULL)))
1797
0
    {
1798
0
        return MP_VAL;
1799
0
    }
1800
1801
    /* zero the carry */
1802
0
    u = 0;
1803
0
    for (i = 0; i < min_ab; i++) {
1804
      /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
1805
0
      *tmpc = *tmpa++ + *tmpb++ + u;
1806
1807
      /* U = carry bit of T[i] */
1808
0
      u = *tmpc >> ((mp_digit)DIGIT_BIT);
1809
1810
      /* take away carry bit from T[i] */
1811
0
      *tmpc++ &= MP_MASK;
1812
0
    }
1813
1814
    /* now copy higher words if any, that is in A+B
1815
     * if A or B has more digits add those in
1816
     */
1817
0
    if (min_ab != max_ab) {
1818
0
      for (; i < max_ab; i++) {
1819
        /* T[i] = X[i] + U */
1820
0
          *tmpc = x->dp[i] + u;
1821
1822
        /* U = carry bit of T[i] */
1823
0
        u = *tmpc >> ((mp_digit)DIGIT_BIT);
1824
1825
        /* take away carry bit from T[i] */
1826
0
        *tmpc++ &= MP_MASK;
1827
0
      }
1828
0
    }
1829
1830
    /* add carry */
1831
0
    *tmpc++ = u;
1832
1833
    /* clear digits above olduse */
1834
0
    for (i = c->used; i < olduse; i++) {
1835
0
      *tmpc++ = 0;
1836
0
    }
1837
0
  }
1838
1839
0
  mp_clamp (c);
1840
0
  return MP_OKAY;
1841
0
}
1842
1843
1844
/* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
1845
int s_mp_sub (mp_int * a, mp_int * b, mp_int * c)
1846
0
{
1847
0
  int     olduse, res, min_b, max_a;
1848
1849
  /* find sizes */
1850
0
  min_b = b->used;
1851
0
  max_a = a->used;
1852
1853
  /* init result */
1854
0
  if (c->alloc < max_a) {
1855
0
    if ((res = mp_grow (c, max_a)) != MP_OKAY) {
1856
0
      return res;
1857
0
    }
1858
0
  }
1859
1860
  /* sanity check on destination */
1861
0
  if (c->dp == NULL)
1862
0
     return MP_VAL;
1863
1864
0
  olduse = c->used;
1865
0
  c->used = max_a;
1866
1867
0
  {
1868
0
    mp_digit u, *tmpa, *tmpb, *tmpc;
1869
0
    int i;
1870
1871
    /* alias for digit pointers */
1872
0
    tmpa = a->dp;
1873
0
    tmpb = b->dp;
1874
0
    tmpc = c->dp;
1875
1876
    /* sanity-check dp pointers from a and b. */
1877
0
    if ((min_b > 0) &&
1878
0
        ((tmpa == NULL) || (tmpb == NULL)))
1879
0
    {
1880
0
        return MP_VAL;
1881
0
    }
1882
1883
    /* set carry to zero */
1884
0
    u = 0;
1885
0
    for (i = 0; i < min_b; i++) {
1886
      /* T[i] = A[i] - B[i] - U */
1887
0
      *tmpc = *tmpa++ - *tmpb++ - u;
1888
1889
      /* U = carry bit of T[i]
1890
       * Note this saves performing an AND operation since
1891
       * if a carry does occur it will propagate all the way to the
1892
       * MSB.  As a result a single shift is enough to get the carry
1893
       */
1894
0
      u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
1895
1896
      /* Clear carry from T[i] */
1897
0
      *tmpc++ &= MP_MASK;
1898
0
    }
1899
1900
    /* now copy higher words if any, e.g. if A has more digits than B  */
1901
0
    for (; i < max_a; i++) {
1902
      /* T[i] = A[i] - U */
1903
0
      *tmpc = *tmpa++ - u;
1904
1905
      /* U = carry bit of T[i] */
1906
0
      u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
1907
1908
      /* Clear carry from T[i] */
1909
0
      *tmpc++ &= MP_MASK;
1910
0
    }
1911
1912
    /* clear digits above used (since we may not have grown result above) */
1913
0
    for (i = c->used; i < olduse; i++) {
1914
0
      *tmpc++ = 0;
1915
0
    }
1916
0
  }
1917
1918
0
  mp_clamp (c);
1919
0
  return MP_OKAY;
1920
0
}
1921
1922
1923
/* high level subtraction (handles signs) */
1924
int mp_sub (mp_int * a, mp_int * b, mp_int * c)
1925
0
{
1926
0
  int     sa, sb, res;
1927
1928
0
  sa = a->sign;
1929
0
  sb = b->sign;
1930
1931
0
  if (sa != sb) {
1932
    /* subtract a negative from a positive, OR */
1933
    /* subtract a positive from a negative. */
1934
    /* In either case, ADD their magnitudes, */
1935
    /* and use the sign of the first number. */
1936
0
    c->sign = sa;
1937
0
    res = s_mp_add (a, b, c);
1938
0
  } else {
1939
    /* subtract a positive from a positive, OR */
1940
    /* subtract a negative from a negative. */
1941
    /* First, take the difference between their */
1942
    /* magnitudes, then... */
1943
0
    if (mp_cmp_mag (a, b) != MP_LT) {
1944
      /* Copy the sign from the first */
1945
0
      c->sign = sa;
1946
      /* The first has a larger or equal magnitude */
1947
0
      res = s_mp_sub (a, b, c);
1948
0
    } else {
1949
      /* The result has the *opposite* sign from */
1950
      /* the first number. */
1951
0
      c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
1952
      /* The second has a larger magnitude */
1953
0
      res = s_mp_sub (b, a, c);
1954
0
    }
1955
0
  }
1956
0
  return res;
1957
0
}
1958
1959
1960
/* determines if reduce_2k_l can be used */
1961
int mp_reduce_is_2k_l(mp_int *a)
1962
0
{
1963
0
   int ix, iy;
1964
1965
0
   if (a->used == 0) {
1966
0
      return MP_NO;
1967
0
   } else if (a->used == 1) {
1968
0
      return MP_YES;
1969
0
   } else if (a->used > 1) {
1970
      /* if more than half of the digits are -1 we're sold */
1971
0
      for (iy = ix = 0; ix < a->used; ix++) {
1972
0
          if (a->dp[ix] == MP_MASK) {
1973
0
              ++iy;
1974
0
          }
1975
0
      }
1976
0
      return (iy >= (a->used/2)) ? MP_YES : MP_NO;
1977
1978
0
   }
1979
0
   return MP_NO;
1980
0
}
1981
1982
1983
/* determines if mp_reduce_2k can be used */
1984
int mp_reduce_is_2k(mp_int *a)
1985
0
{
1986
0
   int ix, iy, iw;
1987
0
   mp_digit iz;
1988
1989
0
   if (a->used == 0) {
1990
0
      return MP_NO;
1991
0
   } else if (a->used == 1) {
1992
0
      return MP_YES;
1993
0
   } else if (a->used > 1) {
1994
0
      iy = mp_count_bits(a);
1995
0
      iz = 1;
1996
0
      iw = 1;
1997
1998
      /* Test every bit from the second digit up, must be 1 */
1999
0
      for (ix = DIGIT_BIT; ix < iy; ix++) {
2000
0
          if ((a->dp[iw] & iz) == 0) {
2001
0
             return MP_NO;
2002
0
          }
2003
0
          iz <<= 1;
2004
0
          if (iz > (mp_digit)MP_MASK) {
2005
0
             ++iw;
2006
0
             iz = 1;
2007
0
          }
2008
0
      }
2009
0
   }
2010
0
   return MP_YES;
2011
0
}
2012
2013
2014
/* determines if a number is a valid DR modulus */
2015
int mp_dr_is_modulus(mp_int *a)
2016
0
{
2017
0
   int ix;
2018
2019
   /* must be at least two digits */
2020
0
   if (a->used < 2) {
2021
0
      return 0;
2022
0
   }
2023
2024
   /* must be of the form b**k - a [a <= b] so all
2025
    * but the first digit must be equal to -1 (mod b).
2026
    */
2027
0
   for (ix = 1; ix < a->used; ix++) {
2028
0
       if (a->dp[ix] != MP_MASK) {
2029
0
          return 0;
2030
0
       }
2031
0
   }
2032
0
   return 1;
2033
0
}
2034
2035
/* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
2036
 *
2037
 * Uses a left-to-right k-ary sliding window to compute the modular
2038
 * exponentiation.
2039
 * The value of k changes based on the size of the exponent.
2040
 *
2041
 * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
2042
 */
2043
2044
#ifdef MP_LOW_MEM
2045
   #define TAB_SIZE 32
2046
#else
2047
   #define TAB_SIZE 256
2048
#endif
2049
2050
int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y,
2051
                     int redmode)
2052
0
{
2053
0
  mp_int res;
2054
0
  mp_digit buf, mp;
2055
0
  int     err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
2056
0
  WC_DECLARE_VAR(M, mp_int, TAB_SIZE, 0);
2057
  /* use a pointer to the reduction algorithm.  This allows us to use
2058
   * one of many reduction algorithms without modding the guts of
2059
   * the code with if statements everywhere.
2060
   */
2061
0
  int     (*redux)(mp_int*,mp_int*,mp_digit) = NULL;
2062
2063
0
  WC_ALLOC_VAR_EX(M, mp_int, TAB_SIZE, NULL, DYNAMIC_TYPE_BIGINT,
2064
0
      return MP_MEM);
2065
2066
  /* find window size */
2067
0
  x = mp_count_bits (X);
2068
0
  if (x <= 7) {
2069
0
    winsize = 2;
2070
0
  } else if (x <= 36) {
2071
0
    winsize = 3;
2072
0
  } else if (x <= 140) {
2073
0
    winsize = 4;
2074
0
  } else if (x <= 450) {
2075
0
    winsize = 5;
2076
0
  } else if (x <= 1303) {
2077
0
    winsize = 6;
2078
0
  } else if (x <= 3529) {
2079
0
    winsize = 7;
2080
0
  } else {
2081
0
    winsize = 8;
2082
0
  }
2083
2084
0
#ifdef MP_LOW_MEM
2085
0
  if (winsize > 5) {
2086
0
     winsize = 5;
2087
0
  }
2088
0
#endif
2089
2090
  /* init M array */
2091
  /* init first cell */
2092
0
  if ((err = mp_init_size(&M[1], P->alloc)) != MP_OKAY) {
2093
0
     WC_FREE_VAR_EX(M, NULL, DYNAMIC_TYPE_BIGINT);
2094
2095
0
     return err;
2096
0
  }
2097
2098
  /* now init the second half of the array */
2099
0
  for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
2100
0
    if ((err = mp_init_size(&M[x], P->alloc)) != MP_OKAY) {
2101
0
      for (y = 1<<(winsize-1); y < x; y++) {
2102
0
        mp_clear (&M[y]);
2103
0
      }
2104
0
      mp_clear(&M[1]);
2105
2106
0
      WC_FREE_VAR_EX(M, NULL, DYNAMIC_TYPE_BIGINT);
2107
2108
0
      return err;
2109
0
    }
2110
0
  }
2111
2112
  /* determine and setup reduction code */
2113
0
  if (redmode == 0) {
2114
0
#ifdef BN_MP_MONTGOMERY_SETUP_C
2115
     /* now setup montgomery  */
2116
0
     if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
2117
0
        goto LBL_M;
2118
0
     }
2119
#else
2120
     err = MP_VAL;
2121
     goto LBL_M;
2122
#endif
2123
2124
     /* automatically pick the comba one if available (saves quite a few
2125
        calls/ifs) */
2126
0
#ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2127
0
     if (((P->used * 2 + 1) < (int)MP_WARRAY) &&
2128
0
          P->used < (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2129
0
        redux = fast_mp_montgomery_reduce;
2130
0
     } else
2131
0
#endif
2132
0
     {
2133
0
#ifdef BN_MP_MONTGOMERY_REDUCE_C
2134
        /* use slower baseline Montgomery method */
2135
0
        redux = mp_montgomery_reduce;
2136
0
#endif
2137
0
     }
2138
0
  } else if (redmode == 1) {
2139
0
#if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C)
2140
     /* setup DR reduction for moduli of the form B**k - b */
2141
0
     mp_dr_setup(P, &mp);
2142
0
     redux = mp_dr_reduce;
2143
0
#endif
2144
0
  } else {
2145
0
#if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C)
2146
     /* setup DR reduction for moduli of the form 2**k - b */
2147
0
     if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) {
2148
0
        goto LBL_M;
2149
0
     }
2150
     /* mp of zero is not usable */
2151
0
     if (mp != 0) {
2152
0
         redux = mp_reduce_2k;
2153
0
     }
2154
0
#endif
2155
0
  }
2156
2157
0
  if (redux == NULL) {
2158
0
     err = MP_VAL;
2159
0
     goto LBL_M;
2160
0
  }
2161
2162
  /* setup result */
2163
0
  if ((err = mp_init_size (&res, P->alloc)) != MP_OKAY) {
2164
0
    goto LBL_M;
2165
0
  }
2166
2167
  /* create M table
2168
   *
2169
2170
   *
2171
   * The first half of the table is not computed though accept for M[0] and M[1]
2172
   */
2173
2174
0
  if (redmode == 0) {
2175
0
#ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
2176
     /* now we need R mod m */
2177
0
     if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) {
2178
0
       goto LBL_RES;
2179
0
     }
2180
2181
     /* now set M[1] to G * R mod m */
2182
0
     if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
2183
0
       goto LBL_RES;
2184
0
     }
2185
#else
2186
     err = MP_VAL;
2187
     goto LBL_RES;
2188
#endif
2189
0
  } else {
2190
0
     if ((err = mp_set(&res, 1)) != MP_OKAY) {
2191
0
        goto LBL_RES;
2192
0
     }
2193
0
     if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
2194
0
        goto LBL_RES;
2195
0
     }
2196
0
  }
2197
2198
  /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times*/
2199
0
  if ((err = mp_copy (&M[1], &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
2200
0
    goto LBL_RES;
2201
0
  }
2202
2203
0
  for (x = 0; x < (winsize - 1); x++) {
2204
0
    if ((err = mp_sqr (&M[(mp_digit)(1 << (winsize - 1))],
2205
0
                       &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
2206
0
      goto LBL_RES;
2207
0
    }
2208
0
    if ((err = redux (&M[(mp_digit)(1 << (winsize - 1))], P, mp)) != MP_OKAY) {
2209
0
      goto LBL_RES;
2210
0
    }
2211
0
  }
2212
2213
  /* create upper table */
2214
0
  for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
2215
0
    if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
2216
0
      goto LBL_RES;
2217
0
    }
2218
0
    if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
2219
0
      goto LBL_RES;
2220
0
    }
2221
0
  }
2222
2223
  /* set initial mode and bit cnt */
2224
0
  mode   = 0;
2225
0
  bitcnt = 1;
2226
0
  buf    = 0;
2227
0
  digidx = X->used - 1;
2228
0
  bitcpy = 0;
2229
0
  bitbuf = 0;
2230
2231
0
  for (;;) {
2232
    /* grab next digit as required */
2233
0
    if (--bitcnt == 0) {
2234
      /* if digidx == -1 we are out of digits so break */
2235
0
      if (digidx == -1) {
2236
0
        break;
2237
0
      }
2238
      /* read next digit and reset bitcnt */
2239
0
      buf    = X->dp[digidx--];
2240
0
      bitcnt = (int)DIGIT_BIT;
2241
0
    }
2242
2243
    /* grab the next msb from the exponent */
2244
0
    y     = (int)(buf >> (DIGIT_BIT - 1)) & 1;
2245
0
    buf <<= (mp_digit)1;
2246
2247
    /* if the bit is zero and mode == 0 then we ignore it
2248
     * These represent the leading zero bits before the first 1 bit
2249
     * in the exponent.  Technically this opt is not required but it
2250
     * does lower the # of trivial squaring/reductions used
2251
     */
2252
0
    if (mode == 0 && y == 0) {
2253
0
      continue;
2254
0
    }
2255
2256
    /* if the bit is zero and mode == 1 then we square */
2257
0
    if (mode == 1 && y == 0) {
2258
0
      if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2259
0
        goto LBL_RES;
2260
0
      }
2261
0
      if ((err = redux (&res, P, mp)) != MP_OKAY) {
2262
0
        goto LBL_RES;
2263
0
      }
2264
0
      continue;
2265
0
    }
2266
2267
    /* else we add it to the window */
2268
0
    bitbuf |= (y << (winsize - ++bitcpy));
2269
0
    mode    = 2;
2270
2271
0
    if (bitcpy == winsize) {
2272
      /* ok window is filled so square as required and multiply  */
2273
      /* square first */
2274
0
      for (x = 0; x < winsize; x++) {
2275
0
        if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2276
0
          goto LBL_RES;
2277
0
        }
2278
0
        if ((err = redux (&res, P, mp)) != MP_OKAY) {
2279
0
          goto LBL_RES;
2280
0
        }
2281
0
      }
2282
2283
      /* then multiply */
2284
0
      if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
2285
0
        goto LBL_RES;
2286
0
      }
2287
0
      if ((err = redux (&res, P, mp)) != MP_OKAY) {
2288
0
        goto LBL_RES;
2289
0
      }
2290
2291
      /* empty window and reset */
2292
0
      bitcpy = 0;
2293
0
      bitbuf = 0;
2294
0
      mode   = 1;
2295
0
    }
2296
0
  }
2297
2298
  /* if bits remain then square/multiply */
2299
0
  if (mode == 2 && bitcpy > 0) {
2300
    /* square then multiply if the bit is set */
2301
0
    for (x = 0; x < bitcpy; x++) {
2302
0
      if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
2303
0
        goto LBL_RES;
2304
0
      }
2305
0
      if ((err = redux (&res, P, mp)) != MP_OKAY) {
2306
0
        goto LBL_RES;
2307
0
      }
2308
2309
      /* get next bit of the window */
2310
0
      bitbuf <<= 1;
2311
0
      if ((bitbuf & (1 << winsize)) != 0) {
2312
        /* then multiply */
2313
0
        if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
2314
0
          goto LBL_RES;
2315
0
        }
2316
0
        if ((err = redux (&res, P, mp)) != MP_OKAY) {
2317
0
          goto LBL_RES;
2318
0
        }
2319
0
      }
2320
0
    }
2321
0
  }
2322
2323
0
  if (redmode == 0) {
2324
     /* fixup result if Montgomery reduction is used
2325
      * recall that any value in a Montgomery system is
2326
      * actually multiplied by R mod n.  So we have
2327
      * to reduce one more time to cancel out the factor
2328
      * of R.
2329
      */
2330
0
     if ((err = redux(&res, P, mp)) != MP_OKAY) {
2331
0
       goto LBL_RES;
2332
0
     }
2333
0
  }
2334
2335
  /* swap res with Y */
2336
0
  mp_exch (&res, Y);
2337
0
  err = MP_OKAY;
2338
0
LBL_RES:mp_clear (&res);
2339
0
LBL_M:
2340
0
  mp_clear(&M[1]);
2341
0
  for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
2342
0
    mp_clear (&M[x]);
2343
0
  }
2344
2345
0
  WC_FREE_VAR_EX(M, NULL, DYNAMIC_TYPE_BIGINT);
2346
2347
0
  return err;
2348
0
}
2349
2350
#ifdef BN_MP_EXPTMOD_BASE_2
2351
#if DIGIT_BIT < 16
2352
    #define WINSIZE    3
2353
#elif DIGIT_BIT < 32
2354
    #define WINSIZE    4
2355
#elif DIGIT_BIT < 64
2356
0
    #define WINSIZE    5
2357
#elif DIGIT_BIT < 128
2358
    #define WINSIZE    6
2359
#endif
2360
int mp_exptmod_base_2(mp_int * X, mp_int * P, mp_int * Y)
2361
0
{
2362
0
  mp_digit buf, mp;
2363
0
  int      err = MP_OKAY, bitbuf, bitcpy, bitcnt, digidx, x, y;
2364
0
  mp_int   res[1];
2365
0
  int     (*redux)(mp_int*,mp_int*,mp_digit) = NULL;
2366
2367
  /* automatically pick the comba one if available (saves quite a few
2368
     calls/ifs) */
2369
0
#ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
2370
0
  if (((P->used * 2 + 1) < (int)MP_WARRAY) &&
2371
0
       P->used < (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2372
0
     redux = fast_mp_montgomery_reduce;
2373
0
  } else
2374
0
#endif
2375
0
#ifdef BN_MP_MONTGOMERY_REDUCE_C
2376
0
  {
2377
     /* use slower baseline Montgomery method */
2378
0
     redux = mp_montgomery_reduce;
2379
0
  }
2380
0
#endif
2381
2382
0
  if (redux == NULL) {
2383
0
      return MP_VAL;
2384
0
  }
2385
2386
  /* now setup montgomery  */
2387
0
  if ((err = mp_montgomery_setup(P, &mp)) != MP_OKAY) {
2388
0
     goto LBL_M;
2389
0
  }
2390
2391
  /* setup result */
2392
0
  if ((err = mp_init(res)) != MP_OKAY) {
2393
0
     goto LBL_M;
2394
0
  }
2395
2396
  /* now we need R mod m */
2397
0
  if ((err = mp_montgomery_calc_normalization(res, P)) != MP_OKAY) {
2398
0
     goto LBL_RES;
2399
0
  }
2400
2401
  /* Get the top bits left over after taking WINSIZE bits starting at the
2402
   * least-significant.
2403
   */
2404
0
  digidx = X->used - 1;
2405
0
  bitcpy = (X->used * DIGIT_BIT) % WINSIZE;
2406
0
  if (bitcpy > 0) {
2407
0
     bitcnt = (int)DIGIT_BIT - bitcpy;
2408
0
     buf    = X->dp[digidx--];
2409
0
     bitbuf = (int)(buf >> bitcnt);
2410
     /* Multiply montgomery representation of 1 by 2 ^ top */
2411
0
     err = mp_mul_2d(res, bitbuf, res);
2412
0
     if (err != MP_OKAY) {
2413
0
        goto LBL_RES;
2414
0
     }
2415
0
     err = mp_mod(res, P, res);
2416
0
     if (err != MP_OKAY) {
2417
0
        goto LBL_RES;
2418
0
     }
2419
     /* Move out bits used */
2420
0
     buf  <<= bitcpy;
2421
0
     bitcnt++;
2422
0
  }
2423
0
  else {
2424
0
     bitcnt = 1;
2425
0
     buf    = 0;
2426
0
  }
2427
2428
  /* empty window and reset  */
2429
0
  bitbuf = 0;
2430
0
  bitcpy = 0;
2431
2432
0
  for (;;) {
2433
    /* grab next digit as required */
2434
0
    if (--bitcnt == 0) {
2435
      /* if digidx == -1 we are out of digits so break */
2436
0
      if (digidx == -1) {
2437
0
        break;
2438
0
      }
2439
      /* read next digit and reset bitcnt */
2440
0
      buf    = X->dp[digidx--];
2441
0
      bitcnt = (int)DIGIT_BIT;
2442
0
    }
2443
2444
    /* grab the next msb from the exponent */
2445
0
    y       = (int)(buf >> (DIGIT_BIT - 1)) & 1;
2446
0
    buf   <<= (mp_digit)1;
2447
    /* add bit to the window */
2448
0
    bitbuf |= (y << (WINSIZE - ++bitcpy));
2449
2450
0
    if (bitcpy == WINSIZE) {
2451
      /* ok window is filled so square as required and multiply  */
2452
      /* square first */
2453
0
      for (x = 0; x < WINSIZE; x++) {
2454
0
        err = mp_sqr(res, res);
2455
0
        if (err != MP_OKAY) {
2456
0
          goto LBL_RES;
2457
0
        }
2458
0
        err = (*redux)(res, P, mp);
2459
0
        if (err != MP_OKAY) {
2460
0
          goto LBL_RES;
2461
0
        }
2462
0
      }
2463
2464
      /* then multiply by 2^bitbuf */
2465
0
      err = mp_mul_2d(res, bitbuf, res);
2466
0
      if (err != MP_OKAY) {
2467
0
         goto LBL_RES;
2468
0
      }
2469
0
      err = mp_mod(res, P, res);
2470
0
      if (err != MP_OKAY) {
2471
0
         goto LBL_RES;
2472
0
      }
2473
2474
      /* empty window and reset */
2475
0
      bitcpy = 0;
2476
0
      bitbuf = 0;
2477
0
    }
2478
0
  }
2479
2480
  /* fixup result if Montgomery reduction is used
2481
   * recall that any value in a Montgomery system is
2482
   * actually multiplied by R mod n.  So we have
2483
   * to reduce one more time to cancel out the factor
2484
   * of R.
2485
   */
2486
0
  err = (*redux)(res, P, mp);
2487
0
  if (err != MP_OKAY) {
2488
0
     goto LBL_RES;
2489
0
  }
2490
2491
  /* swap res with Y */
2492
0
  err = mp_copy(res, Y);
2493
2494
0
LBL_RES:mp_clear (res);
2495
0
LBL_M:
2496
0
  return err;
2497
0
}
2498
2499
#undef WINSIZE
2500
#endif /* BN_MP_EXPTMOD_BASE_2 */
2501
2502
2503
/* setups the montgomery reduction stuff */
2504
int mp_montgomery_setup (mp_int * n, mp_digit * rho)
2505
0
{
2506
0
  mp_digit x, b;
2507
2508
/* fast inversion mod 2**k
2509
 *
2510
 * Based on the fact that
2511
 *
2512
 * XA = 1 (mod 2**n)  =>  (X(2-XA)) A = 1 (mod 2**2n)
2513
 *                    =>  2*X*A - X*X*A*A = 1
2514
 *                    =>  2*(1) - (1)     = 1
2515
 */
2516
0
  b = n->dp[0];
2517
2518
0
  if ((b & 1) == 0) {
2519
0
    return MP_VAL;
2520
0
  }
2521
2522
0
  x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
2523
0
  x *= 2 - b * x;               /* here x*a==1 mod 2**8 */
2524
0
#if !defined(MP_8BIT)
2525
0
  x *= 2 - b * x;               /* here x*a==1 mod 2**16 */
2526
0
#endif
2527
0
#if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
2528
0
  x *= 2 - b * x;               /* here x*a==1 mod 2**32 */
2529
0
#endif
2530
0
#ifdef MP_64BIT
2531
0
  x *= 2 - b * x;               /* here x*a==1 mod 2**64 */
2532
0
#endif
2533
2534
  /* rho = -1/m mod b */
2535
  /* TAO, switched mp_word casts to mp_digit to shut up compiler */
2536
0
  *rho = (mp_digit)((((mp_digit)1 << ((mp_digit) DIGIT_BIT)) - x) & MP_MASK);
2537
2538
0
  return MP_OKAY;
2539
0
}
2540
2541
2542
/* computes xR**-1 == x (mod N) via Montgomery Reduction
2543
 *
2544
 * This is an optimized implementation of montgomery_reduce
2545
 * which uses the comba method to quickly calculate the columns of the
2546
 * reduction.
2547
 *
2548
 * Based on Algorithm 14.32 on pp.601 of HAC.
2549
*/
2550
int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
2551
0
{
2552
0
  int     ix, res, olduse;
2553
  /* uses dynamic memory and slower */
2554
0
  WC_DECLARE_VAR(W, mp_word, MP_WARRAY, 0);
2555
2556
  /* get old used count */
2557
0
  olduse = x->used;
2558
2559
  /* grow a as required */
2560
0
  if (x->alloc < n->used + 1) {
2561
0
    if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) {
2562
0
      return res;
2563
0
    }
2564
0
  }
2565
2566
0
  WC_ALLOC_VAR_EX(W, mp_word, (n->used*2+2), NULL, DYNAMIC_TYPE_BIGINT,
2567
0
      return MP_MEM);
2568
2569
0
  XMEMSET(W, 0, sizeof(mp_word) * (n->used * 2 + 2));
2570
2571
  /* first we have to get the digits of the input into
2572
   * an array of double precision words W[...]
2573
   */
2574
0
  {
2575
0
    mp_word *_W;
2576
0
    mp_digit *tmpx;
2577
2578
    /* alias for the W[] array */
2579
0
    _W   = W;
2580
2581
    /* alias for the digits of  x*/
2582
0
    tmpx = x->dp;
2583
2584
    /* copy the digits of a into W[0..a->used-1] */
2585
0
    for (ix = 0; ix < x->used; ix++) {
2586
0
      *_W++ = *tmpx++;
2587
0
    }
2588
0
  }
2589
2590
  /* now we proceed to zero successive digits
2591
   * from the least significant upwards
2592
   */
2593
0
  for (ix = 0; ix < n->used; ix++) {
2594
    /* mu = ai * m' mod b
2595
     *
2596
     * We avoid a double precision multiplication (which isn't required)
2597
     * by casting the value down to a mp_digit.  Note this requires
2598
     * that W[ix-1] have  the carry cleared (see after the inner loop)
2599
     */
2600
0
    mp_digit mu;
2601
0
    mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK);
2602
2603
    /* a = a + mu * m * b**i
2604
     *
2605
     * This is computed in place and on the fly.  The multiplication
2606
     * by b**i is handled by offsetting which columns the results
2607
     * are added to.
2608
     *
2609
     * Note the comba method normally doesn't handle carries in the
2610
     * inner loop In this case we fix the carry from the previous
2611
     * column since the Montgomery reduction requires digits of the
2612
     * result (so far) [see above] to work.  This is
2613
     * handled by fixing up one carry after the inner loop.  The
2614
     * carry fixups are done in order so after these loops the
2615
     * first m->used words of W[] have the carries fixed
2616
     */
2617
0
    {
2618
0
      int iy;
2619
0
      mp_digit *tmpn;
2620
0
      mp_word *_W;
2621
2622
      /* alias for the digits of the modulus */
2623
0
      tmpn = n->dp;
2624
2625
      /* Alias for the columns set by an offset of ix */
2626
0
      _W = W + ix;
2627
2628
      /* inner loop */
2629
0
      for (iy = 0; iy < n->used; iy++) {
2630
0
          *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++);
2631
0
      }
2632
0
    }
2633
2634
    /* now fix carry for next digit, W[ix+1] */
2635
0
    W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT);
2636
0
  }
2637
2638
  /* now we have to propagate the carries and
2639
   * shift the words downward [all those least
2640
   * significant digits we zeroed].
2641
   */
2642
0
  {
2643
0
    mp_digit *tmpx;
2644
0
    mp_word *_W, *_W1;
2645
2646
    /* nox fix rest of carries */
2647
2648
    /* alias for current word */
2649
0
    _W1 = W + ix;
2650
2651
    /* alias for next word, where the carry goes */
2652
0
    _W = W + ++ix;
2653
2654
0
    for (; ix <= n->used * 2 + 1; ix++) {
2655
0
      *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT);
2656
0
    }
2657
2658
    /* copy out, A = A/b**n
2659
     *
2660
     * The result is A/b**n but instead of converting from an
2661
     * array of mp_word to mp_digit than calling mp_rshd
2662
     * we just copy them in the right order
2663
     */
2664
2665
    /* alias for destination word */
2666
0
    tmpx = x->dp;
2667
2668
    /* alias for shifted double precision result */
2669
0
    _W = W + n->used;
2670
2671
0
    for (ix = 0; ix < n->used + 1; ix++) {
2672
0
      *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK));
2673
0
    }
2674
2675
    /* zero olduse digits, if the input a was larger than
2676
     * m->used+1 we'll have to clear the digits
2677
     */
2678
0
    for (; ix < olduse; ix++) {
2679
0
      *tmpx++ = 0;
2680
0
    }
2681
0
  }
2682
2683
  /* set the max used and clamp */
2684
0
  x->used = n->used + 1;
2685
0
  mp_clamp (x);
2686
2687
0
  WC_FREE_VAR_EX(W, NULL, DYNAMIC_TYPE_BIGINT);
2688
2689
  /* if A >= m then A = A - m */
2690
0
  if (mp_cmp_mag (x, n) != MP_LT) {
2691
0
    return s_mp_sub (x, n, x);
2692
0
  }
2693
0
  return MP_OKAY;
2694
0
}
2695
2696
2697
/* computes xR**-1 == x (mod N) via Montgomery Reduction */
2698
int mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
2699
0
{
2700
0
  int     ix, res, digs;
2701
0
  mp_digit mu;
2702
2703
  /* can the fast reduction [comba] method be used?
2704
   *
2705
   * Note that unlike in mul you're safely allowed *less*
2706
   * than the available columns [255 per default] since carries
2707
   * are fixed up in the inner loop.
2708
   */
2709
0
  digs = n->used * 2 + 1;
2710
0
  if ((digs < (int)MP_WARRAY) &&
2711
0
      n->used <
2712
0
      (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
2713
0
    return fast_mp_montgomery_reduce (x, n, rho);
2714
0
  }
2715
2716
  /* grow the input as required */
2717
0
  if (x->alloc < digs) {
2718
0
    if ((res = mp_grow (x, digs)) != MP_OKAY) {
2719
0
      return res;
2720
0
    }
2721
0
  }
2722
0
  x->used = digs;
2723
2724
0
  for (ix = 0; ix < n->used; ix++) {
2725
    /* mu = ai * rho mod b
2726
     *
2727
     * The value of rho must be precalculated via
2728
     * montgomery_setup() such that
2729
     * it equals -1/n0 mod b this allows the
2730
     * following inner loop to reduce the
2731
     * input one digit at a time
2732
     */
2733
0
    mu = (mp_digit) (((mp_word)x->dp[ix]) * ((mp_word)rho) & MP_MASK);
2734
2735
    /* a = a + mu * m * b**i */
2736
0
    {
2737
0
      int iy;
2738
0
      mp_digit *tmpn, *tmpx, u;
2739
0
      mp_word r;
2740
2741
      /* alias for digits of the modulus */
2742
0
      tmpn = n->dp;
2743
2744
      /* alias for the digits of x [the input] */
2745
0
      tmpx = x->dp + ix;
2746
2747
      /* set the carry to zero */
2748
0
      u = 0;
2749
2750
      /* Multiply and add in place */
2751
0
      for (iy = 0; iy < n->used; iy++) {
2752
        /* compute product and sum */
2753
0
        r       = ((mp_word)mu) * ((mp_word)*tmpn++) +
2754
0
                  ((mp_word) u) + ((mp_word) * tmpx);
2755
2756
        /* get carry */
2757
0
        u       = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
2758
2759
        /* fix digit */
2760
0
        *tmpx++ = (mp_digit)(r & ((mp_word) MP_MASK));
2761
0
      }
2762
      /* At this point the ix'th digit of x should be zero */
2763
2764
2765
      /* propagate carries upwards as required*/
2766
0
      while (u) {
2767
0
        *tmpx   += u;
2768
0
        u        = *tmpx >> DIGIT_BIT;
2769
0
        *tmpx++ &= MP_MASK;
2770
0
      }
2771
0
    }
2772
0
  }
2773
2774
  /* at this point the n.used'th least
2775
   * significant digits of x are all zero
2776
   * which means we can shift x to the
2777
   * right by n.used digits and the
2778
   * residue is unchanged.
2779
   */
2780
2781
  /* x = x/b**n.used */
2782
0
  mp_clamp(x);
2783
0
  mp_rshd (x, n->used);
2784
2785
  /* if x >= n then x = x - n */
2786
0
  if (mp_cmp_mag (x, n) != MP_LT) {
2787
0
    return s_mp_sub (x, n, x);
2788
0
  }
2789
2790
0
  return MP_OKAY;
2791
0
}
2792
2793
2794
/* determines the setup value */
2795
void mp_dr_setup(mp_int *a, mp_digit *d)
2796
0
{
2797
   /* the casts are required if DIGIT_BIT is one less than
2798
    * the number of bits in a mp_digit [e.g. DIGIT_BIT==31]
2799
    */
2800
0
   *d = (mp_digit)((((mp_word)1) << ((mp_word)DIGIT_BIT)) -
2801
0
        ((mp_word)a->dp[0]));
2802
0
}
2803
2804
2805
/* reduce "x" in place modulo "n" using the Diminished Radix algorithm.
2806
 *
2807
 * Based on algorithm from the paper
2808
 *
2809
 * "Generating Efficient Primes for Discrete Log Cryptosystems"
2810
 *                 Chae Hoon Lim, Pil Joong Lee,
2811
 *          POSTECH Information Research Laboratories
2812
 *
2813
 * The modulus must be of a special format [see manual]
2814
 *
2815
 * Has been modified to use algorithm 7.10 from the LTM book instead
2816
 *
2817
 * Input x must be in the range 0 <= x <= (n-1)**2
2818
 */
2819
int mp_dr_reduce (mp_int * x, mp_int * n, mp_digit k)
2820
0
{
2821
0
  int      err, i, m;
2822
0
  mp_word  r;
2823
0
  mp_digit mu, *tmpx1, *tmpx2;
2824
2825
  /* m = digits in modulus */
2826
0
  m = n->used;
2827
2828
  /* ensure that "x" has at least 2m digits */
2829
0
  if (x->alloc < m + m) {
2830
0
    if ((err = mp_grow (x, m + m)) != MP_OKAY) {
2831
0
      return err;
2832
0
    }
2833
0
  }
2834
2835
/* top of loop, this is where the code resumes if
2836
 * another reduction pass is required.
2837
 */
2838
0
top:
2839
  /* aliases for digits */
2840
  /* alias for lower half of x */
2841
0
  tmpx1 = x->dp;
2842
2843
  /* alias for upper half of x, or x/B**m */
2844
0
  tmpx2 = x->dp + m;
2845
2846
  /* set carry to zero */
2847
0
  mu = 0;
2848
2849
  /* compute (x mod B**m) + k * [x/B**m] inline and inplace */
2850
0
  for (i = 0; i < m; i++) {
2851
0
      r         = ((mp_word)*tmpx2++) * ((mp_word)k) + *tmpx1 + mu;
2852
0
      *tmpx1++  = (mp_digit)(r & MP_MASK);
2853
0
      mu        = (mp_digit)(r >> ((mp_word)DIGIT_BIT));
2854
0
  }
2855
2856
  /* set final carry */
2857
0
  *tmpx1++ = mu;
2858
2859
  /* zero words above m */
2860
0
  for (i = m + 1; i < x->used; i++) {
2861
0
      *tmpx1++ = 0;
2862
0
  }
2863
2864
  /* clamp, sub and return */
2865
0
  mp_clamp (x);
2866
2867
  /* if x >= n then subtract and reduce again
2868
   * Each successive "recursion" makes the input smaller and smaller.
2869
   */
2870
0
  if (mp_cmp_mag (x, n) != MP_LT) {
2871
0
    if ((err = s_mp_sub(x, n, x)) != MP_OKAY) {
2872
0
        return err;
2873
0
    }
2874
0
    goto top;
2875
0
  }
2876
0
  return MP_OKAY;
2877
0
}
2878
2879
2880
/* reduces a modulo n where n is of the form 2**p - d */
2881
int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d)
2882
0
{
2883
0
   mp_int q;
2884
0
   int    p, res;
2885
2886
0
   if ((res = mp_init(&q)) != MP_OKAY) {
2887
0
      return res;
2888
0
   }
2889
2890
0
   p = mp_count_bits(n);
2891
0
top:
2892
   /* q = a/2**p, a = a mod 2**p */
2893
0
   if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
2894
0
      goto ERR;
2895
0
   }
2896
2897
0
   if (d != 1) {
2898
      /* q = q * d */
2899
0
      if ((res = mp_mul_d(&q, d, &q)) != MP_OKAY) {
2900
0
         goto ERR;
2901
0
      }
2902
0
   }
2903
2904
   /* a = a + q */
2905
0
   if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
2906
0
      goto ERR;
2907
0
   }
2908
2909
0
   if (mp_cmp_mag(a, n) != MP_LT) {
2910
0
      if ((res = s_mp_sub(a, n, a)) != MP_OKAY) {
2911
0
         goto ERR;
2912
0
      }
2913
0
      goto top;
2914
0
   }
2915
2916
0
ERR:
2917
0
   mp_clear(&q);
2918
0
   return res;
2919
0
}
2920
2921
2922
/* determines the setup value */
2923
int mp_reduce_2k_setup(mp_int *a, mp_digit *d)
2924
0
{
2925
0
   int res, p;
2926
0
   mp_int tmp;
2927
2928
0
   if ((res = mp_init(&tmp)) != MP_OKAY) {
2929
0
      return res;
2930
0
   }
2931
2932
0
   p = mp_count_bits(a);
2933
0
   if ((res = mp_2expt(&tmp, p)) != MP_OKAY) {
2934
0
      mp_clear(&tmp);
2935
0
      return res;
2936
0
   }
2937
2938
0
   if ((res = s_mp_sub(&tmp, a, &tmp)) != MP_OKAY) {
2939
0
      mp_clear(&tmp);
2940
0
      return res;
2941
0
   }
2942
2943
0
   *d = tmp.dp[0];
2944
0
   mp_clear(&tmp);
2945
0
   return MP_OKAY;
2946
0
}
2947
2948
2949
/* set the b bit of a */
2950
int mp_set_bit (mp_int * a, int b)
2951
0
{
2952
0
    int i = b / DIGIT_BIT, res;
2953
2954
    /*
2955
     * Require:
2956
     *  bit index b >= 0
2957
     *  a->alloc == a->used == 0 if a->dp == NULL
2958
     */
2959
0
    if (b < 0 || (a->dp == NULL && (a->alloc != 0 || a->used != 0)))
2960
0
        return MP_VAL;
2961
2962
0
    if (a->dp == NULL || a->used < (int)(i + 1)) {
2963
        /* grow a to accommodate the single bit */
2964
0
        if ((res = mp_grow (a, i + 1)) != MP_OKAY) {
2965
0
            return res;
2966
0
        }
2967
2968
        /* set the used count of where the bit will go */
2969
0
        a->used = (int)(i + 1);
2970
0
    }
2971
2972
    /* put the single bit in its place */
2973
0
    a->dp[i] |= ((mp_digit)1) << (b % DIGIT_BIT);
2974
2975
0
    return MP_OKAY;
2976
0
}
2977
2978
/* computes a = 2**b
2979
 *
2980
 * Simple algorithm which zeros the int, set the required bit
2981
 */
2982
int mp_2expt (mp_int * a, int b)
2983
0
{
2984
    /* zero a as per default */
2985
0
    mp_zero (a);
2986
2987
0
    return mp_set_bit(a, b);
2988
0
}
2989
2990
/* multiply by a digit */
2991
int mp_mul_d (mp_int * a, mp_digit b, mp_int * c)
2992
0
{
2993
0
  mp_digit u, *tmpa, *tmpc;
2994
0
  mp_word  r;
2995
0
  int      ix, res, olduse;
2996
2997
  /* make sure c is big enough to hold a*b */
2998
0
  if (c->dp == NULL || c->alloc < a->used + 1) {
2999
0
    if ((res = mp_grow (c, a->used + 1)) != MP_OKAY) {
3000
0
      return res;
3001
0
    }
3002
0
  }
3003
3004
  /* get the original destinations used count */
3005
0
  olduse = c->used;
3006
3007
  /* set the sign */
3008
0
  c->sign = a->sign;
3009
3010
  /* alias for a->dp [source] */
3011
0
  tmpa = a->dp;
3012
3013
  /* alias for c->dp [dest] */
3014
0
  tmpc = c->dp;
3015
3016
  /* zero carry */
3017
0
  u = 0;
3018
3019
  /* compute columns */
3020
0
  for (ix = 0; ix < a->used; ix++) {
3021
    /* compute product and carry sum for this term */
3022
0
    r       = ((mp_word) u) + ((mp_word)*tmpa++) * ((mp_word)b);
3023
3024
    /* mask off higher bits to get a single digit */
3025
0
    *tmpc++ = (mp_digit) (r & ((mp_word) MP_MASK));
3026
3027
    /* send carry into next iteration */
3028
0
    u       = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
3029
0
  }
3030
3031
  /* store final carry [if any] and increment ix offset  */
3032
0
  *tmpc++ = u;
3033
0
  ++ix;
3034
3035
  /* now zero digits above the top */
3036
0
  while (ix++ < olduse) {
3037
0
     *tmpc++ = 0;
3038
0
  }
3039
3040
  /* set used count */
3041
0
  c->used = a->used + 1;
3042
0
  mp_clamp(c);
3043
3044
0
  return MP_OKAY;
3045
0
}
3046
3047
3048
/* d = a * b (mod c) */
3049
#if defined(FREESCALE_LTC_TFM)
3050
int wolfcrypt_mp_mulmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d)
3051
#else
3052
int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
3053
#endif
3054
0
{
3055
0
  int     res;
3056
0
  mp_int  t;
3057
3058
0
  if ((res = mp_init_size (&t, c->used)) != MP_OKAY) {
3059
0
    return res;
3060
0
  }
3061
3062
0
  res = mp_mul (a, b, &t);
3063
0
  if (res == MP_OKAY) {
3064
0
      res = mp_mod (&t, c, d);
3065
0
  }
3066
3067
0
  mp_clear (&t);
3068
0
  return res;
3069
0
}
3070
3071
3072
/* d = a - b (mod c) */
3073
int mp_submod(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
3074
0
{
3075
0
  int     res;
3076
0
  mp_int  t;
3077
3078
0
  if ((res = mp_init (&t)) != MP_OKAY) {
3079
0
    return res;
3080
0
  }
3081
3082
0
  res = mp_sub (a, b, &t);
3083
0
  if (res == MP_OKAY) {
3084
0
      res = mp_mod (&t, c, d);
3085
0
  }
3086
3087
0
  mp_clear (&t);
3088
3089
0
  return res;
3090
0
}
3091
3092
/* d = a + b (mod c) */
3093
int mp_addmod(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
3094
0
{
3095
0
  int     res;
3096
0
  mp_int  t;
3097
3098
0
  if ((res = mp_init (&t)) != MP_OKAY) {
3099
0
    return res;
3100
0
  }
3101
3102
0
  res = mp_add (a, b, &t);
3103
0
  if (res == MP_OKAY) {
3104
0
    res = mp_mod (&t, c, d);
3105
0
  }
3106
3107
0
  mp_clear (&t);
3108
3109
0
  return res;
3110
0
}
3111
3112
/* d = a - b (mod c) - a < c and b < c and positive */
3113
int mp_submod_ct(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
3114
0
{
3115
0
  int     res;
3116
0
  mp_int  t;
3117
0
  mp_int* r = d;
3118
3119
0
  if (c == d) {
3120
0
    r = &t;
3121
3122
0
    if ((res = mp_init (r)) != MP_OKAY) {
3123
0
      return res;
3124
0
    }
3125
0
  }
3126
3127
0
  res = mp_sub (a, b, r);
3128
0
  if (res == MP_OKAY) {
3129
0
    if (mp_isneg (r)) {
3130
0
      res = mp_add (r, c, d);
3131
0
    } else if (c == d) {
3132
0
      res = mp_copy (r, d);
3133
0
    }
3134
0
  }
3135
3136
0
  if (c == d) {
3137
0
    mp_clear (r);
3138
0
  }
3139
3140
0
  return res;
3141
0
}
3142
3143
/* d = a + b (mod c) - a < c and b < c and positive */
3144
int mp_addmod_ct(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
3145
0
{
3146
0
  int     res;
3147
0
  mp_int  t;
3148
0
  mp_int* r = d;
3149
3150
0
  if (c == d) {
3151
0
    r = &t;
3152
3153
0
    if ((res = mp_init (r)) != MP_OKAY) {
3154
0
      return res;
3155
0
    }
3156
0
  }
3157
3158
0
  res = mp_add (a, b, r);
3159
0
  if (res == MP_OKAY) {
3160
0
    if (mp_cmp (r, c) != MP_LT) {
3161
0
      res = mp_sub (r, c, d);
3162
0
    } else if (c == d) {
3163
0
      res = mp_copy (r, d);
3164
0
    }
3165
0
  }
3166
3167
0
  if (c == d) {
3168
0
    mp_clear (r);
3169
0
  }
3170
3171
0
  return res;
3172
0
}
3173
3174
/* computes b = a*a */
3175
int mp_sqr (mp_int * a, mp_int * b)
3176
0
{
3177
0
  int     res;
3178
3179
0
  {
3180
0
#ifdef BN_FAST_S_MP_SQR_C
3181
    /* can we use the fast comba multiplier? */
3182
0
    if ((a->used * 2 + 1) < (int)MP_WARRAY &&
3183
0
         a->used <
3184
0
         (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) {
3185
0
      res = fast_s_mp_sqr (a, b);
3186
0
    } else
3187
0
#endif
3188
0
#ifdef BN_S_MP_SQR_C
3189
0
      res = s_mp_sqr (a, b);
3190
#else
3191
      res = MP_VAL;
3192
#endif
3193
0
  }
3194
0
  b->sign = MP_ZPOS;
3195
0
  return res;
3196
0
}
3197
3198
3199
/* high level multiplication (handles sign) */
3200
#if defined(FREESCALE_LTC_TFM)
3201
int wolfcrypt_mp_mul(mp_int *a, mp_int *b, mp_int *c)
3202
#else
3203
int mp_mul (mp_int * a, mp_int * b, mp_int * c)
3204
#endif
3205
0
{
3206
0
  int     res, neg;
3207
0
  neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
3208
3209
0
  {
3210
0
#ifdef BN_FAST_S_MP_MUL_DIGS_C
3211
    /* can we use the fast multiplier?
3212
     *
3213
     * The fast multiplier can be used if the output will
3214
     * have less than MP_WARRAY digits and the number of
3215
     * digits won't affect carry propagation
3216
     */
3217
0
    int     digs = a->used + b->used + 1;
3218
3219
0
    if ((digs < (int)MP_WARRAY) &&
3220
0
        MIN(a->used, b->used) <=
3221
0
        (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
3222
0
      res = fast_s_mp_mul_digs (a, b, c, digs);
3223
0
    } else
3224
0
#endif
3225
0
#ifdef BN_S_MP_MUL_DIGS_C
3226
0
      res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */
3227
#else
3228
      res = MP_VAL;
3229
#endif
3230
3231
0
  }
3232
0
  c->sign = (c->used > 0) ? neg : MP_ZPOS;
3233
0
  return res;
3234
0
}
3235
3236
3237
/* b = a*2 */
3238
int mp_mul_2(mp_int * a, mp_int * b)
3239
0
{
3240
0
  int     x, res, oldused;
3241
3242
  /* grow to accommodate result */
3243
0
  if (b->alloc < a->used + 1) {
3244
0
    if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) {
3245
0
      return res;
3246
0
    }
3247
0
  }
3248
3249
0
  oldused = b->used;
3250
0
  b->used = a->used;
3251
3252
0
  {
3253
0
    mp_digit r, rr, *tmpa, *tmpb;
3254
3255
    /* alias for source */
3256
0
    tmpa = a->dp;
3257
3258
    /* alias for dest */
3259
0
    tmpb = b->dp;
3260
3261
    /* carry */
3262
0
    r = 0;
3263
0
    for (x = 0; x < a->used; x++) {
3264
3265
      /* get what will be the *next* carry bit from the
3266
       * MSB of the current digit
3267
       */
3268
0
      rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1));
3269
3270
      /* now shift up this digit, add in the carry [from the previous] */
3271
0
      *tmpb++ = (mp_digit)(((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK);
3272
3273
      /* copy the carry that would be from the source
3274
       * digit into the next iteration
3275
       */
3276
0
      r = rr;
3277
0
    }
3278
3279
    /* new leading digit? */
3280
0
    if (r != 0) {
3281
      /* add a MSB which is always 1 at this point */
3282
0
      *tmpb = 1;
3283
0
      ++(b->used);
3284
0
    }
3285
3286
    /* now zero any excess digits on the destination
3287
     * that we didn't write to
3288
     */
3289
0
    tmpb = b->dp + b->used;
3290
0
    for (x = b->used; x < oldused; x++) {
3291
0
      *tmpb++ = 0;
3292
0
    }
3293
0
  }
3294
0
  b->sign = a->sign;
3295
0
  return MP_OKAY;
3296
0
}
3297
3298
3299
/* divide by three (based on routine from MPI and the GMP manual) */
3300
int mp_div_3 (mp_int * a, mp_int *c, mp_digit * d)
3301
0
{
3302
0
  mp_int   q;
3303
0
  mp_word  w, t;
3304
0
  mp_digit b;
3305
0
  int      res, ix;
3306
3307
  /* b = 2**DIGIT_BIT / 3 */
3308
0
  b = (mp_digit) ( (((mp_word)1) << ((mp_word)DIGIT_BIT)) / ((mp_word)3) );
3309
3310
0
  if ((res = mp_init_size(&q, a->used)) != MP_OKAY) {
3311
0
     return res;
3312
0
  }
3313
3314
0
  q.used = a->used;
3315
0
  q.sign = a->sign;
3316
0
  w = 0;
3317
3318
0
  if (a->used == 0) {
3319
0
      mp_clear(&q);
3320
0
      return MP_VAL;
3321
0
  }
3322
3323
0
  for (ix = a->used - 1; ix >= 0; ix--) {
3324
0
     w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]);
3325
3326
0
     if (w >= 3) {
3327
        /* multiply w by [1/3] */
3328
0
        t = (w * ((mp_word)b)) >> ((mp_word)DIGIT_BIT);
3329
3330
        /* now subtract 3 * [w/3] from w, to get the remainder */
3331
0
        w -= t+t+t;
3332
3333
        /* fixup the remainder as required since
3334
         * the optimization is not exact.
3335
         */
3336
0
        while (w >= 3) {
3337
0
           t += 1;
3338
0
           w -= 3;
3339
0
        }
3340
0
      } else {
3341
0
        t = 0;
3342
0
      }
3343
0
      q.dp[ix] = (mp_digit)t;
3344
0
  }
3345
3346
  /* [optional] store the remainder */
3347
0
  if (d != NULL) {
3348
0
     *d = (mp_digit)w;
3349
0
  }
3350
3351
  /* [optional] store the quotient */
3352
0
  if (c != NULL) {
3353
0
     mp_clamp(&q);
3354
0
     mp_exch(&q, c);
3355
0
  }
3356
0
  mp_clear(&q);
3357
3358
0
  return res;
3359
0
}
3360
3361
3362
/* init an mp_init for a given size */
3363
int mp_init_size (mp_int * a, int size)
3364
0
{
3365
  /* pad size so there are always extra digits */
3366
0
  size += (MP_PREC * 2) - (size % MP_PREC);
3367
3368
  /* alloc mem */
3369
0
  a->dp = (mp_digit *)XMALLOC (sizeof (mp_digit) * size, NULL,
3370
0
                                      DYNAMIC_TYPE_BIGINT);
3371
0
  if (a->dp == NULL) {
3372
0
    return MP_MEM;
3373
0
  }
3374
3375
  /* set the members */
3376
0
  a->used  = 0;
3377
0
  a->alloc = size;
3378
0
  a->sign  = MP_ZPOS;
3379
#ifdef HAVE_WOLF_BIGINT
3380
  wc_bigint_init(&a->raw);
3381
#endif
3382
3383
  /* zero the digits */
3384
0
  XMEMSET(a->dp, 0, sizeof (mp_digit) * size);
3385
3386
0
  return MP_OKAY;
3387
0
}
3388
3389
3390
/* the list of squaring...
3391
 * you do like mult except the offset of the tmpx [one that
3392
 * starts closer to zero] can't equal the offset of tmpy.
3393
 * So basically you set up iy like before then you min it with
3394
 * (ty-tx) so that it never happens.  You double all those
3395
 * you add in the inner loop
3396
3397
After that loop you do the squares and add them in.
3398
*/
3399
3400
int fast_s_mp_sqr (mp_int * a, mp_int * b)
3401
0
{
3402
0
  int       olduse, res, pa, ix, iz;
3403
  /* uses dynamic memory and slower */
3404
0
  WC_DECLARE_VAR(W, mp_digit, MP_WARRAY, 0);
3405
0
  mp_digit  *tmpx;
3406
0
  mp_word   W1;
3407
3408
  /* grow the destination as required */
3409
0
  pa = a->used + a->used;
3410
0
  if (b->alloc < pa) {
3411
0
    if ((res = mp_grow (b, pa)) != MP_OKAY) {
3412
0
      return res;
3413
0
    }
3414
0
  }
3415
3416
0
  if (pa > (int)MP_WARRAY)
3417
0
    return MP_RANGE;  /* TAO range check */
3418
3419
0
  if (pa == 0) {
3420
    /* Nothing to do. Zero result and return. */
3421
0
    mp_zero(b);
3422
0
    return MP_OKAY;
3423
0
  }
3424
3425
0
  WC_ALLOC_VAR_EX(W, mp_digit, pa, NULL, DYNAMIC_TYPE_BIGINT,
3426
0
      return MP_MEM);
3427
3428
  /* number of output digits to produce */
3429
0
  W1 = 0;
3430
0
  for (ix = 0; ix < pa; ix++) {
3431
0
      int      tx, ty, iy;
3432
0
      mp_word  _W;
3433
0
      mp_digit *tmpy;
3434
3435
      /* clear counter */
3436
0
      _W = 0;
3437
3438
      /* get offsets into the two bignums */
3439
0
      ty = MIN(a->used-1, ix);
3440
0
      tx = ix - ty;
3441
3442
      /* setup temp aliases */
3443
0
      tmpx = a->dp + tx;
3444
0
      tmpy = a->dp + ty;
3445
3446
      /* this is the number of times the loop will iterate, essentially
3447
         while (tx++ < a->used && ty-- >= 0) { ... }
3448
       */
3449
0
      iy = MIN(a->used-tx, ty+1);
3450
3451
      /* now for squaring tx can never equal ty
3452
       * we halve the distance since they approach at a rate of 2x
3453
       * and we have to round because odd cases need to be executed
3454
       */
3455
0
      iy = MIN(iy, (ty-tx+1)>>1);
3456
3457
      /* execute loop */
3458
0
      for (iz = 0; iz < iy; iz++) {
3459
0
         _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
3460
0
      }
3461
3462
      /* double the inner product and add carry */
3463
0
      _W = _W + _W + W1;
3464
3465
      /* even columns have the square term in them */
3466
0
      if ((ix&1) == 0) {
3467
0
         _W += ((mp_word)a->dp[ix>>1])*((mp_word)a->dp[ix>>1]);
3468
0
      }
3469
3470
      /* store it */
3471
0
      W[ix] = (mp_digit)(_W & MP_MASK);
3472
3473
      /* make next carry */
3474
0
      W1 = _W >> ((mp_word)DIGIT_BIT);
3475
0
  }
3476
3477
  /* setup dest */
3478
0
  olduse  = b->used;
3479
0
  b->used = a->used+a->used;
3480
3481
0
  {
3482
0
    mp_digit *tmpb;
3483
0
    tmpb = b->dp;
3484
0
    for (ix = 0; ix < pa; ix++) {
3485
0
      *tmpb++ = (mp_digit)(W[ix] & MP_MASK);
3486
0
    }
3487
3488
    /* clear unused digits [that existed in the old copy of c] */
3489
0
    for (; ix < olduse; ix++) {
3490
0
      *tmpb++ = 0;
3491
0
    }
3492
0
  }
3493
0
  mp_clamp (b);
3494
3495
0
  WC_FREE_VAR_EX(W, NULL, DYNAMIC_TYPE_BIGINT);
3496
3497
0
  return MP_OKAY;
3498
0
}
3499
3500
3501
/* Fast (comba) multiplier
3502
 *
3503
 * This is the fast column-array [comba] multiplier.  It is
3504
 * designed to compute the columns of the product first
3505
 * then handle the carries afterwards.  This has the effect
3506
 * of making the nested loops that compute the columns very
3507
 * simple and schedulable on super-scalar processors.
3508
 *
3509
 * This has been modified to produce a variable number of
3510
 * digits of output so if say only a half-product is required
3511
 * you don't have to compute the upper half (a feature
3512
 * required for fast Barrett reduction).
3513
 *
3514
 * Based on Algorithm 14.12 on pp.595 of HAC.
3515
 *
3516
 */
3517
int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
3518
0
{
3519
0
  int     olduse, res, pa, ix, iz;
3520
  /* uses dynamic memory and slower */
3521
0
  WC_DECLARE_VAR(W, mp_digit, MP_WARRAY, 0);
3522
0
  mp_word  _W;
3523
3524
  /* grow the destination as required */
3525
0
  if (c->alloc < digs) {
3526
0
    if ((res = mp_grow (c, digs)) != MP_OKAY) {
3527
0
      return res;
3528
0
    }
3529
0
  }
3530
3531
  /* number of output digits to produce */
3532
0
  pa = MIN(digs, a->used + b->used);
3533
0
  if (pa > (int)MP_WARRAY)
3534
0
    return MP_RANGE;  /* TAO range check */
3535
3536
0
  if (pa == 0) {
3537
    /* Nothing to do. Zero result and return. */
3538
0
    mp_zero(c);
3539
0
    return MP_OKAY;
3540
0
  }
3541
3542
0
  WC_ALLOC_VAR_EX(W, mp_digit, pa, NULL, DYNAMIC_TYPE_BIGINT,
3543
0
      return MP_MEM);
3544
3545
  /* clear the carry */
3546
0
  _W = 0;
3547
0
  for (ix = 0; ix < pa; ix++) {
3548
0
      int      tx, ty;
3549
0
      int      iy;
3550
0
      mp_digit *tmpx, *tmpy;
3551
3552
0
      if ((a->used > 0) && (b->used > 0)) {
3553
          /* get offsets into the two bignums */
3554
0
          ty = MIN(b->used-1, ix);
3555
0
          tx = ix - ty;
3556
3557
          /* setup temp aliases */
3558
0
          tmpx = a->dp + tx;
3559
0
          tmpy = b->dp + ty;
3560
3561
          /* this is the number of times the loop will iterate, essentially
3562
             while (tx++ < a->used && ty-- >= 0) { ... }
3563
          */
3564
0
          iy = MIN(a->used-tx, ty+1);
3565
3566
          /* execute loop */
3567
0
          for (iz = 0; iz < iy; ++iz) {
3568
0
              _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
3569
3570
0
          }
3571
0
      }
3572
3573
      /* store term */
3574
0
      W[ix] = (mp_digit)(((mp_digit)_W) & MP_MASK);
3575
3576
      /* make next carry */
3577
0
      _W = _W >> ((mp_word)DIGIT_BIT);
3578
0
 }
3579
3580
  /* setup dest */
3581
0
  olduse  = c->used;
3582
0
  c->used = pa;
3583
3584
0
  {
3585
0
    mp_digit *tmpc;
3586
0
    tmpc = c->dp;
3587
0
    for (ix = 0; ix < pa; ix++) { /* JRB, +1 could read uninitialized data */
3588
      /* now extract the previous digit [below the carry] */
3589
0
      *tmpc++ = W[ix];
3590
0
    }
3591
3592
    /* clear unused digits [that existed in the old copy of c] */
3593
0
    for (; ix < olduse; ix++) {
3594
0
      *tmpc++ = 0;
3595
0
    }
3596
0
  }
3597
0
  mp_clamp (c);
3598
3599
0
  WC_FREE_VAR_EX(W, NULL, DYNAMIC_TYPE_BIGINT);
3600
3601
0
  return MP_OKAY;
3602
0
}
3603
3604
3605
/* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
3606
int s_mp_sqr (mp_int * a, mp_int * b)
3607
0
{
3608
0
  mp_int  t;
3609
0
  int     res, ix, iy, pa;
3610
0
  mp_word r;
3611
0
  mp_digit u, tmpx, *tmpt;
3612
3613
0
  pa = a->used;
3614
0
  if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
3615
0
    return res;
3616
0
  }
3617
3618
  /* default used is maximum possible size */
3619
0
  t.used = 2*pa + 1;
3620
3621
0
  for (ix = 0; ix < pa; ix++) {
3622
    /* first calculate the digit at 2*ix */
3623
    /* calculate double precision result */
3624
0
    r = ((mp_word) t.dp[2*ix]) +
3625
0
        ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]);
3626
3627
    /* store lower part in result */
3628
0
    t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
3629
3630
    /* get the carry */
3631
0
    u           = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
3632
3633
    /* left hand side of A[ix] * A[iy] */
3634
0
    tmpx        = a->dp[ix];
3635
3636
    /* alias for where to store the results */
3637
0
    tmpt        = t.dp + (2*ix + 1);
3638
3639
0
    for (iy = ix + 1; iy < pa; iy++) {
3640
      /* first calculate the product */
3641
0
      r       = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
3642
3643
      /* now calculate the double precision result, note we use
3644
       * addition instead of *2 since it's easier to optimize
3645
       */
3646
0
      r       = ((mp_word) *tmpt) + r + r + ((mp_word) u);
3647
3648
      /* store lower part */
3649
0
      *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
3650
3651
      /* get carry */
3652
0
      u       = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
3653
0
    }
3654
    /* propagate upwards */
3655
0
    while (u != ((mp_digit) 0)) {
3656
0
      r       = ((mp_word) *tmpt) + ((mp_word) u);
3657
0
      *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
3658
0
      u       = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
3659
0
    }
3660
0
  }
3661
3662
0
  mp_clamp (&t);
3663
0
  mp_exch (&t, b);
3664
0
  mp_clear (&t);
3665
0
  return MP_OKAY;
3666
0
}
3667
3668
3669
/* multiplies |a| * |b| and only computes up to digs digits of result
3670
 * HAC pp. 595, Algorithm 14.12  Modified so you can control how
3671
 * many digits of output are created.
3672
 */
3673
int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
3674
0
{
3675
0
  mp_int  t;
3676
0
  int     res, pa, pb, ix, iy;
3677
0
  mp_digit u;
3678
0
  mp_word r;
3679
0
  mp_digit tmpx, *tmpt, *tmpy;
3680
3681
  /* can we use the fast multiplier? */
3682
0
  if ((digs < (int)MP_WARRAY) &&
3683
0
      MIN (a->used, b->used) <
3684
0
          (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
3685
0
    return fast_s_mp_mul_digs (a, b, c, digs);
3686
0
  }
3687
3688
0
  if ((res = mp_init_size (&t, digs)) != MP_OKAY) {
3689
0
    return res;
3690
0
  }
3691
0
  t.used = digs;
3692
3693
  /* compute the digits of the product directly */
3694
0
  pa = a->used;
3695
0
  for (ix = 0; ix < pa; ix++) {
3696
    /* set the carry to zero */
3697
0
    u = 0;
3698
3699
    /* limit ourselves to making digs digits of output */
3700
0
    pb = MIN (b->used, digs - ix);
3701
3702
    /* setup some aliases */
3703
    /* copy of the digit from a used within the nested loop */
3704
0
    tmpx = a->dp[ix];
3705
3706
    /* an alias for the destination shifted ix places */
3707
0
    tmpt = t.dp + ix;
3708
3709
    /* an alias for the digits of b */
3710
0
    tmpy = b->dp;
3711
3712
    /* compute the columns of the output and propagate the carry */
3713
0
    for (iy = 0; iy < pb; iy++) {
3714
      /* compute the column as a mp_word */
3715
0
      r       = ((mp_word)*tmpt) +
3716
0
                ((mp_word)tmpx) * ((mp_word)*tmpy++) +
3717
0
                ((mp_word) u);
3718
3719
      /* the new column is the lower part of the result */
3720
0
      *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
3721
3722
      /* get the carry word from the result */
3723
0
      u       = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
3724
0
    }
3725
    /* set carry if it is placed below digs */
3726
0
    if (ix + iy < digs) {
3727
0
      *tmpt = u;
3728
0
    }
3729
0
  }
3730
3731
0
  mp_clamp (&t);
3732
0
  mp_exch (&t, c);
3733
3734
0
  mp_clear (&t);
3735
0
  return MP_OKAY;
3736
0
}
3737
3738
3739
/*
3740
 * shifts with subtractions when the result is greater than b.
3741
 *
3742
 * The method is slightly modified to shift B unconditionally up to just under
3743
 * the leading bit of b.  This saves a lot of multiple precision shifting.
3744
 */
3745
int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
3746
0
{
3747
0
  int     x, bits, res;
3748
3749
  /* how many bits of last digit does b use */
3750
0
  bits = mp_count_bits (b) % DIGIT_BIT;
3751
3752
0
  if (b->used > 1) {
3753
0
     if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1))
3754
0
         != MP_OKAY) {
3755
0
        return res;
3756
0
     }
3757
0
  } else {
3758
0
     if ((res = mp_set(a, 1)) != MP_OKAY) {
3759
0
        return res;
3760
0
     }
3761
0
     bits = 1;
3762
0
  }
3763
3764
  /* now compute C = A * B mod b */
3765
0
  for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
3766
0
    if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
3767
0
      return res;
3768
0
    }
3769
0
    if (mp_cmp_mag (a, b) != MP_LT) {
3770
0
      if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
3771
0
        return res;
3772
0
      }
3773
0
    }
3774
0
  }
3775
3776
0
  return MP_OKAY;
3777
0
}
3778
3779
3780
#ifdef MP_LOW_MEM
3781
   #define TAB_SIZE 32
3782
#else
3783
   #define TAB_SIZE 256
3784
#endif
3785
3786
int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
3787
0
{
3788
0
  mp_int  M[TAB_SIZE], res, mu;
3789
0
  mp_digit buf;
3790
0
  int     err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
3791
0
  int (*redux)(mp_int*,mp_int*,mp_int*);
3792
3793
  /* find window size */
3794
0
  x = mp_count_bits (X);
3795
0
  if (x <= 7) {
3796
0
    winsize = 2;
3797
0
  } else if (x <= 36) {
3798
0
    winsize = 3;
3799
0
  } else if (x <= 140) {
3800
0
    winsize = 4;
3801
0
  } else if (x <= 450) {
3802
0
    winsize = 5;
3803
0
  } else if (x <= 1303) {
3804
0
    winsize = 6;
3805
0
  } else if (x <= 3529) {
3806
0
    winsize = 7;
3807
0
  } else {
3808
0
    winsize = 8;
3809
0
  }
3810
3811
0
#ifdef MP_LOW_MEM
3812
0
    if (winsize > 5) {
3813
0
       winsize = 5;
3814
0
    }
3815
0
#endif
3816
3817
  /* init M array */
3818
  /* init first cell */
3819
0
  if ((err = mp_init(&M[1])) != MP_OKAY) {
3820
0
     return err;
3821
0
  }
3822
3823
  /* now init the second half of the array */
3824
0
  for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
3825
0
    if ((err = mp_init(&M[x])) != MP_OKAY) {
3826
0
      for (y = 1<<(winsize-1); y < x; y++) {
3827
0
        mp_clear (&M[y]);
3828
0
      }
3829
0
      mp_clear(&M[1]);
3830
0
      return err;
3831
0
    }
3832
0
  }
3833
3834
  /* create mu, used for Barrett reduction */
3835
0
  if ((err = mp_init (&mu)) != MP_OKAY) {
3836
0
    goto LBL_M;
3837
0
  }
3838
3839
0
  if (redmode == 0) {
3840
0
     if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) {
3841
0
        goto LBL_MU;
3842
0
     }
3843
0
     redux = mp_reduce;
3844
0
  } else {
3845
0
     if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) {
3846
0
        goto LBL_MU;
3847
0
     }
3848
0
     redux = mp_reduce_2k_l;
3849
0
  }
3850
3851
  /* create M table
3852
   *
3853
   * The M table contains powers of the base,
3854
   * e.g. M[x] = G**x mod P
3855
   *
3856
   * The first half of the table is not
3857
   * computed though accept for M[0] and M[1]
3858
   */
3859
0
  if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) {
3860
0
    goto LBL_MU;
3861
0
  }
3862
3863
  /* compute the value at M[1<<(winsize-1)] by squaring
3864
   * M[1] (winsize-1) times
3865
   */
3866
0
  if ((err = mp_copy (&M[1], &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
3867
0
    goto LBL_MU;
3868
0
  }
3869
3870
0
  for (x = 0; x < (winsize - 1); x++) {
3871
    /* square it */
3872
0
    if ((err = mp_sqr (&M[(mp_digit)(1 << (winsize - 1))],
3873
0
                       &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
3874
0
      goto LBL_MU;
3875
0
    }
3876
3877
    /* reduce modulo P */
3878
0
    if ((err = redux (&M[(mp_digit)(1 << (winsize - 1))], P, &mu)) != MP_OKAY) {
3879
0
      goto LBL_MU;
3880
0
    }
3881
0
  }
3882
3883
  /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
3884
   * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
3885
   */
3886
0
  for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
3887
0
    if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
3888
0
      goto LBL_MU;
3889
0
    }
3890
0
    if ((err = redux (&M[x], P, &mu)) != MP_OKAY) {
3891
0
      goto LBL_MU;
3892
0
    }
3893
0
  }
3894
3895
  /* setup result */
3896
0
  if ((err = mp_init (&res)) != MP_OKAY) {
3897
0
    goto LBL_MU;
3898
0
  }
3899
0
  if ((err = mp_set (&res, 1)) != MP_OKAY) {
3900
0
    goto LBL_MU;
3901
0
  }
3902
3903
  /* set initial mode and bit cnt */
3904
0
  mode   = 0;
3905
0
  bitcnt = 1;
3906
0
  buf    = 0;
3907
0
  digidx = X->used - 1;
3908
0
  bitcpy = 0;
3909
0
  bitbuf = 0;
3910
3911
0
  for (;;) {
3912
    /* grab next digit as required */
3913
0
    if (--bitcnt == 0) {
3914
      /* if digidx == -1 we are out of digits */
3915
0
      if (digidx == -1) {
3916
0
        break;
3917
0
      }
3918
      /* read next digit and reset the bitcnt */
3919
0
      buf    = X->dp[digidx--];
3920
0
      bitcnt = (int) DIGIT_BIT;
3921
0
    }
3922
3923
    /* grab the next msb from the exponent */
3924
0
    y     = (int)(buf >> (mp_digit)(DIGIT_BIT - 1)) & 1;
3925
0
    buf <<= (mp_digit)1;
3926
3927
    /* if the bit is zero and mode == 0 then we ignore it
3928
     * These represent the leading zero bits before the first 1 bit
3929
     * in the exponent.  Technically this opt is not required but it
3930
     * does lower the # of trivial squaring/reductions used
3931
     */
3932
0
    if (mode == 0 && y == 0) {
3933
0
      continue;
3934
0
    }
3935
3936
    /* if the bit is zero and mode == 1 then we square */
3937
0
    if (mode == 1 && y == 0) {
3938
0
      if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3939
0
        goto LBL_RES;
3940
0
      }
3941
0
      if ((err = redux (&res, P, &mu)) != MP_OKAY) {
3942
0
        goto LBL_RES;
3943
0
      }
3944
0
      continue;
3945
0
    }
3946
3947
    /* else we add it to the window */
3948
0
    bitbuf |= (y << (winsize - ++bitcpy));
3949
0
    mode    = 2;
3950
3951
0
    if (bitcpy == winsize) {
3952
      /* ok window is filled so square as required and multiply  */
3953
      /* square first */
3954
0
      for (x = 0; x < winsize; x++) {
3955
0
        if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3956
0
          goto LBL_RES;
3957
0
        }
3958
0
        if ((err = redux (&res, P, &mu)) != MP_OKAY) {
3959
0
          goto LBL_RES;
3960
0
        }
3961
0
      }
3962
3963
      /* then multiply */
3964
0
      if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
3965
0
        goto LBL_RES;
3966
0
      }
3967
0
      if ((err = redux (&res, P, &mu)) != MP_OKAY) {
3968
0
        goto LBL_RES;
3969
0
      }
3970
3971
      /* empty window and reset */
3972
0
      bitcpy = 0;
3973
0
      bitbuf = 0;
3974
0
      mode   = 1;
3975
0
    }
3976
0
  }
3977
3978
  /* if bits remain then square/multiply */
3979
0
  if (mode == 2 && bitcpy > 0) {
3980
    /* square then multiply if the bit is set */
3981
0
    for (x = 0; x < bitcpy; x++) {
3982
0
      if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
3983
0
        goto LBL_RES;
3984
0
      }
3985
0
      if ((err = redux (&res, P, &mu)) != MP_OKAY) {
3986
0
        goto LBL_RES;
3987
0
      }
3988
3989
0
      bitbuf <<= 1;
3990
0
      if ((bitbuf & (1 << winsize)) != 0) {
3991
        /* then multiply */
3992
0
        if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
3993
0
          goto LBL_RES;
3994
0
        }
3995
0
        if ((err = redux (&res, P, &mu)) != MP_OKAY) {
3996
0
          goto LBL_RES;
3997
0
        }
3998
0
      }
3999
0
    }
4000
0
  }
4001
4002
0
  mp_exch (&res, Y);
4003
0
  err = MP_OKAY;
4004
0
LBL_RES:mp_clear (&res);
4005
0
LBL_MU:mp_clear (&mu);
4006
0
LBL_M:
4007
0
  mp_clear(&M[1]);
4008
0
  for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
4009
0
    mp_clear (&M[x]);
4010
0
  }
4011
0
  return err;
4012
0
}
4013
4014
4015
/* pre-calculate the value required for Barrett reduction
4016
 * For a given modulus "b" it calculates the value required in "a"
4017
 */
4018
int mp_reduce_setup (mp_int * a, mp_int * b)
4019
0
{
4020
0
  int     res;
4021
4022
0
  if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) {
4023
0
    return res;
4024
0
  }
4025
0
  return mp_div (a, b, a, NULL);
4026
0
}
4027
4028
4029
/* reduces x mod m, assumes 0 < x < m**2, mu is
4030
 * precomputed via mp_reduce_setup.
4031
 * From HAC pp.604 Algorithm 14.42
4032
 */
4033
int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
4034
0
{
4035
0
  mp_int  q;
4036
0
  int     res, um = m->used;
4037
4038
  /* q = x */
4039
0
  if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
4040
0
    return res;
4041
0
  }
4042
4043
  /* q1 = x / b**(k-1)  */
4044
0
  mp_rshd (&q, um - 1);
4045
4046
  /* according to HAC this optimization is ok */
4047
0
  if (((mp_word) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) {
4048
0
    if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) {
4049
0
      goto CLEANUP;
4050
0
    }
4051
0
  } else {
4052
0
#ifdef BN_S_MP_MUL_HIGH_DIGS_C
4053
0
    if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
4054
0
      goto CLEANUP;
4055
0
    }
4056
#elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C)
4057
    if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
4058
      goto CLEANUP;
4059
    }
4060
#else
4061
    {
4062
      res = MP_VAL;
4063
      goto CLEANUP;
4064
    }
4065
#endif
4066
0
  }
4067
4068
  /* q3 = q2 / b**(k+1) */
4069
0
  mp_rshd (&q, um + 1);
4070
4071
  /* x = x mod b**(k+1), quick (no division) */
4072
0
  if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
4073
0
    goto CLEANUP;
4074
0
  }
4075
4076
  /* q = q * m mod b**(k+1), quick (no division) */
4077
0
  if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) {
4078
0
    goto CLEANUP;
4079
0
  }
4080
4081
  /* x = x - q */
4082
0
  if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
4083
0
    goto CLEANUP;
4084
0
  }
4085
4086
  /* If x < 0, add b**(k+1) to it */
4087
0
  if (mp_cmp_d (x, 0) == MP_LT) {
4088
0
    if ((res = mp_set (&q, 1)) != MP_OKAY)
4089
0
        goto CLEANUP;
4090
0
    if ((res = mp_lshd (&q, um + 1)) != MP_OKAY)
4091
0
      goto CLEANUP;
4092
0
    if ((res = mp_add (x, &q, x)) != MP_OKAY)
4093
0
      goto CLEANUP;
4094
0
  }
4095
4096
  /* Back off if it's too big */
4097
0
  while (mp_cmp (x, m) != MP_LT) {
4098
0
    if ((res = s_mp_sub (x, m, x)) != MP_OKAY) {
4099
0
      goto CLEANUP;
4100
0
    }
4101
0
  }
4102
4103
0
CLEANUP:
4104
0
  mp_clear (&q);
4105
4106
0
  return res;
4107
0
}
4108
4109
4110
/* reduces a modulo n where n is of the form 2**p - d
4111
   This differs from reduce_2k since "d" can be larger
4112
   than a single digit.
4113
*/
4114
int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
4115
0
{
4116
0
   mp_int q;
4117
0
   int    p, res;
4118
4119
0
   if ((res = mp_init(&q)) != MP_OKAY) {
4120
0
      return res;
4121
0
   }
4122
4123
0
   p = mp_count_bits(n);
4124
0
top:
4125
   /* q = a/2**p, a = a mod 2**p */
4126
0
   if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
4127
0
      goto ERR;
4128
0
   }
4129
4130
   /* q = q * d */
4131
0
   if ((res = mp_mul(&q, d, &q)) != MP_OKAY) {
4132
0
      goto ERR;
4133
0
   }
4134
4135
   /* a = a + q */
4136
0
   if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
4137
0
      goto ERR;
4138
0
   }
4139
4140
0
   if (mp_cmp_mag(a, n) != MP_LT) {
4141
0
      if ((res = s_mp_sub(a, n, a)) != MP_OKAY) {
4142
0
         goto ERR;
4143
0
      }
4144
0
      goto top;
4145
0
   }
4146
4147
0
ERR:
4148
0
   mp_clear(&q);
4149
0
   return res;
4150
0
}
4151
4152
4153
/* determines the setup value */
4154
int mp_reduce_2k_setup_l(mp_int *a, mp_int *d)
4155
0
{
4156
0
   int    res;
4157
0
   mp_int tmp;
4158
4159
0
   if ((res = mp_init(&tmp)) != MP_OKAY) {
4160
0
      return res;
4161
0
   }
4162
4163
0
   if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
4164
0
      goto ERR;
4165
0
   }
4166
4167
0
   if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
4168
0
      goto ERR;
4169
0
   }
4170
4171
0
ERR:
4172
0
   mp_clear(&tmp);
4173
0
   return res;
4174
0
}
4175
4176
4177
/* multiplies |a| * |b| and does not compute the lower digs digits
4178
 * [meant to get the higher part of the product]
4179
 */
4180
int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
4181
0
{
4182
0
  mp_int  t;
4183
0
  int     res, pa, pb, ix, iy;
4184
0
  mp_digit u;
4185
0
  mp_word r;
4186
0
  mp_digit tmpx, *tmpt, *tmpy;
4187
4188
  /* can we use the fast multiplier? */
4189
0
#ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C
4190
0
  if (((a->used + b->used + 1) < (int)MP_WARRAY)
4191
0
      && MIN (a->used, b->used) <
4192
0
      (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
4193
0
    return fast_s_mp_mul_high_digs (a, b, c, digs);
4194
0
  }
4195
0
#endif
4196
4197
0
  if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) {
4198
0
    return res;
4199
0
  }
4200
0
  t.used = a->used + b->used + 1;
4201
4202
0
  pa = a->used;
4203
0
  pb = b->used;
4204
0
  for (ix = 0; ix < pa && a->dp; ix++) {
4205
    /* clear the carry */
4206
0
    u = 0;
4207
4208
    /* left hand side of A[ix] * B[iy] */
4209
0
    tmpx = a->dp[ix];
4210
4211
    /* alias to the address of where the digits will be stored */
4212
0
    tmpt = &(t.dp[digs]);
4213
4214
    /* alias for where to read the right hand side from */
4215
0
    tmpy = b->dp + (digs - ix);
4216
4217
0
    for (iy = digs - ix; iy < pb; iy++) {
4218
      /* calculate the double precision result */
4219
0
      r       = ((mp_word)*tmpt) +
4220
0
                ((mp_word)tmpx) * ((mp_word)*tmpy++) +
4221
0
                ((mp_word) u);
4222
4223
      /* get the lower part */
4224
0
      *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
4225
4226
      /* carry the carry */
4227
0
      u       = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
4228
0
    }
4229
0
    *tmpt = u;
4230
0
  }
4231
0
  mp_clamp (&t);
4232
0
  mp_exch (&t, c);
4233
0
  mp_clear (&t);
4234
0
  return MP_OKAY;
4235
0
}
4236
4237
4238
/* this is a modified version of fast_s_mul_digs that only produces
4239
 * output digits *above* digs.  See the comments for fast_s_mul_digs
4240
 * to see how it works.
4241
 *
4242
 * This is used in the Barrett reduction since for one of the multiplications
4243
 * only the higher digits were needed.  This essentially halves the work.
4244
 *
4245
 * Based on Algorithm 14.12 on pp.595 of HAC.
4246
 */
4247
int fast_s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
4248
0
{
4249
0
  int     olduse, res, pa, ix, iz;
4250
  /* uses dynamic memory and slower */
4251
0
  WC_DECLARE_VAR(W, mp_digit, MP_WARRAY, 0);
4252
0
  mp_word  _W;
4253
4254
0
  if (a->dp == NULL) { /* JRB, avoid reading uninitialized values */
4255
0
      return MP_VAL;
4256
0
  }
4257
4258
  /* grow the destination as required */
4259
0
  pa = a->used + b->used;
4260
0
  if (c->alloc < pa) {
4261
0
    if ((res = mp_grow (c, pa)) != MP_OKAY) {
4262
0
      return res;
4263
0
    }
4264
0
  }
4265
4266
0
  if (pa > (int)MP_WARRAY)
4267
0
    return MP_RANGE;  /* TAO range check */
4268
4269
0
  WC_ALLOC_VAR_EX(W, mp_digit, pa, NULL, DYNAMIC_TYPE_BIGINT,
4270
0
      return MP_MEM);
4271
4272
  /* number of output digits to produce */
4273
0
  _W = 0;
4274
0
  for (ix = digs; ix < pa; ix++) { /* JRB, have a->dp check at top of function*/
4275
0
      int      tx, ty, iy;
4276
0
      mp_digit *tmpx, *tmpy;
4277
4278
      /* get offsets into the two bignums */
4279
0
      ty = MIN(b->used-1, ix);
4280
0
      tx = ix - ty;
4281
4282
      /* setup temp aliases */
4283
0
      tmpx = a->dp + tx;
4284
0
      tmpy = b->dp + ty;
4285
4286
      /* this is the number of times the loop will iterate, essentially its
4287
         while (tx++ < a->used && ty-- >= 0) { ... }
4288
       */
4289
0
      iy = MIN(a->used-tx, ty+1);
4290
4291
      /* execute loop */
4292
0
      for (iz = 0; iz < iy; iz++) {
4293
0
         _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
4294
0
      }
4295
4296
      /* store term */
4297
0
      W[ix] = (mp_digit)(((mp_digit)_W) & MP_MASK);
4298
4299
      /* make next carry */
4300
0
      _W = _W >> ((mp_word)DIGIT_BIT);
4301
0
  }
4302
4303
  /* setup dest */
4304
0
  olduse  = c->used;
4305
0
  c->used = pa;
4306
4307
0
  {
4308
0
    mp_digit *tmpc;
4309
4310
0
    tmpc = c->dp + digs;
4311
0
    for (ix = digs; ix < pa; ix++) {   /* TAO, <= could potentially overwrite */
4312
      /* now extract the previous digit [below the carry] */
4313
0
      *tmpc++ = W[ix];
4314
0
    }
4315
4316
    /* clear unused digits [that existed in the old copy of c] */
4317
0
    for (; ix < olduse; ix++) {
4318
0
      *tmpc++ = 0;
4319
0
    }
4320
0
  }
4321
0
  mp_clamp (c);
4322
4323
0
  WC_FREE_VAR_EX(W, NULL, DYNAMIC_TYPE_BIGINT);
4324
4325
0
  return MP_OKAY;
4326
0
}
4327
4328
4329
#ifndef MP_SET_CHUNK_BITS
4330
0
    #define MP_SET_CHUNK_BITS 4
4331
#endif
4332
int mp_set_int (mp_int * a, unsigned long b)
4333
0
{
4334
0
  int x, res;
4335
4336
  /* use direct mp_set if b is less than mp_digit max */
4337
0
  if (b < MP_DIGIT_MAX) {
4338
0
    return mp_set (a, (mp_digit)b);
4339
0
  }
4340
4341
0
  mp_zero (a);
4342
4343
  /* set chunk bits at a time */
4344
0
  for (x = 0; x < (int)(sizeof(b) * 8) / MP_SET_CHUNK_BITS; x++) {
4345
    /* shift the number up chunk bits */
4346
0
    if ((res = mp_mul_2d (a, MP_SET_CHUNK_BITS, a)) != MP_OKAY) {
4347
0
      return res;
4348
0
    }
4349
4350
    /* OR in the top bits of the source */
4351
0
    a->dp[0] |= (b >> ((sizeof(b) * 8) - MP_SET_CHUNK_BITS)) &
4352
0
                                  ((1 << MP_SET_CHUNK_BITS) - 1);
4353
4354
    /* shift the source up to the next chunk bits */
4355
0
    b <<= MP_SET_CHUNK_BITS;
4356
4357
    /* ensure that digits are not clamped off */
4358
0
    a->used += 1;
4359
0
  }
4360
0
  mp_clamp (a);
4361
0
  return MP_OKAY;
4362
0
}
4363
4364
4365
#if defined(WOLFSSL_KEY_GEN) || defined(HAVE_ECC) || !defined(NO_RSA) || \
4366
    !defined(NO_DSA) | !defined(NO_DH)
4367
4368
/* c = a * a (mod b) */
4369
int mp_sqrmod (mp_int * a, mp_int * b, mp_int * c)
4370
0
{
4371
0
  int     res;
4372
0
  mp_int  t;
4373
4374
0
  if ((res = mp_init (&t)) != MP_OKAY) {
4375
0
    return res;
4376
0
  }
4377
4378
0
  if ((res = mp_sqr (a, &t)) != MP_OKAY) {
4379
0
    mp_clear (&t);
4380
0
    return res;
4381
0
  }
4382
0
  res = mp_mod (&t, b, c);
4383
0
  mp_clear (&t);
4384
0
  return res;
4385
0
}
4386
4387
#endif
4388
4389
4390
#if defined(HAVE_ECC) || !defined(NO_PWDBASED) || defined(WOLFSSL_SNIFFER) || \
4391
    defined(WOLFSSL_HAVE_WOLFSCEP) || defined(WOLFSSL_KEY_GEN) || \
4392
    defined(OPENSSL_EXTRA) || defined(WC_RSA_BLINDING) || \
4393
    (!defined(NO_RSA) && !defined(NO_RSA_BOUNDS_CHECK))
4394
4395
/* single digit addition */
4396
int mp_add_d (mp_int* a, mp_digit b, mp_int* c) /* //NOLINT(misc-no-recursion) */
4397
0
{
4398
0
  int     res, ix, oldused;
4399
0
  mp_digit *tmpa, *tmpc, mu;
4400
4401
0
  if (b > MP_DIGIT_MAX) return MP_VAL;
4402
4403
  /* grow c as required */
4404
0
  if (c->alloc < a->used + 1) {
4405
0
     if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) {
4406
0
        return res;
4407
0
     }
4408
0
  }
4409
4410
  /* if a is negative and |a| >= b, call c = |a| - b */
4411
0
  if (a->sign == MP_NEG && (a->used > 1 || a->dp[0] >= b)) {
4412
     /* temporarily fix sign of a */
4413
0
     a->sign = MP_ZPOS;
4414
4415
     /* c = |a| - b */
4416
0
     res = mp_sub_d(a, b, c);
4417
4418
     /* fix sign  */
4419
0
     a->sign = c->sign = MP_NEG;
4420
4421
     /* clamp */
4422
0
     mp_clamp(c);
4423
4424
0
     return res;
4425
0
  }
4426
4427
  /* old number of used digits in c */
4428
0
  oldused = c->used;
4429
4430
  /* source alias */
4431
0
  tmpa    = a->dp;
4432
4433
  /* destination alias */
4434
0
  tmpc    = c->dp;
4435
4436
0
  if (tmpa == NULL || tmpc == NULL) {
4437
0
    return MP_MEM;
4438
0
  }
4439
4440
  /* if a is positive */
4441
0
  if (a->sign == MP_ZPOS) {
4442
     /* add digit, after this we're propagating
4443
      * the carry.
4444
      */
4445
0
     *tmpc   = *tmpa++ + b;
4446
0
     mu      = *tmpc >> DIGIT_BIT;
4447
0
     *tmpc++ &= MP_MASK;
4448
4449
     /* now handle rest of the digits */
4450
0
     for (ix = 1; ix < a->used; ix++) {
4451
0
        *tmpc   = *tmpa++ + mu;
4452
0
        mu      = *tmpc >> DIGIT_BIT;
4453
0
        *tmpc++ &= MP_MASK;
4454
0
     }
4455
     /* set final carry */
4456
0
     if (ix < c->alloc) {
4457
0
        ix++;
4458
0
        *tmpc++  = mu;
4459
0
     }
4460
4461
     /* setup size */
4462
0
     c->used = a->used + 1;
4463
0
  } else {
4464
     /* a was negative and |a| < b */
4465
0
     c->used  = 1;
4466
4467
     /* the result is a single digit */
4468
0
     if (a->used == 1) {
4469
0
        *tmpc++  =  b - a->dp[0];
4470
0
     } else {
4471
0
        *tmpc++  =  b;
4472
0
     }
4473
4474
     /* setup count so the clearing of oldused
4475
      * can fall through correctly
4476
      */
4477
0
     ix       = 1;
4478
0
  }
4479
4480
  /* sign always positive */
4481
0
  c->sign = MP_ZPOS;
4482
4483
  /* now zero to oldused */
4484
0
  while (ix++ < oldused) {
4485
0
     *tmpc++ = 0;
4486
0
  }
4487
0
  mp_clamp(c);
4488
4489
0
  return MP_OKAY;
4490
0
}
4491
4492
4493
/* single digit subtraction */
4494
int mp_sub_d (mp_int * a, mp_digit b, mp_int * c) /* //NOLINT(misc-no-recursion) */
4495
0
{
4496
0
  mp_digit *tmpa, *tmpc, mu;
4497
0
  int       res, ix, oldused;
4498
4499
0
  if (b > MP_MASK) return MP_VAL;
4500
4501
  /* grow c as required */
4502
0
  if (c->alloc < a->used + 1) {
4503
0
     if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) {
4504
0
        return res;
4505
0
     }
4506
0
  }
4507
4508
  /* if a is negative just do an unsigned
4509
   * addition [with fudged signs]
4510
   */
4511
0
  if (a->sign == MP_NEG) {
4512
0
     a->sign = MP_ZPOS;
4513
0
     res     = mp_add_d(a, b, c);
4514
0
     a->sign = c->sign = MP_NEG;
4515
4516
     /* clamp */
4517
0
     mp_clamp(c);
4518
4519
0
     return res;
4520
0
  }
4521
4522
  /* setup regs */
4523
0
  oldused = c->used;
4524
0
  tmpa    = a->dp;
4525
0
  tmpc    = c->dp;
4526
4527
0
  if (tmpa == NULL || tmpc == NULL) {
4528
0
    return MP_MEM;
4529
0
  }
4530
4531
  /* if a <= b simply fix the single digit */
4532
0
  if ((a->used == 1 && a->dp[0] <= b) || a->used == 0) {
4533
0
     if (a->used == 1) {
4534
0
        *tmpc++ = b - *tmpa;
4535
0
     } else {
4536
0
        *tmpc++ = b;
4537
0
     }
4538
0
     ix      = 1;
4539
4540
     /* negative/1digit */
4541
0
     c->sign = MP_NEG;
4542
0
     c->used = 1;
4543
0
  } else {
4544
     /* positive/size */
4545
0
     c->sign = MP_ZPOS;
4546
0
     c->used = a->used;
4547
4548
     /* subtract first digit */
4549
0
     *tmpc    = *tmpa++ - b;
4550
0
     mu       = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
4551
0
     *tmpc++ &= MP_MASK;
4552
4553
     /* handle rest of the digits */
4554
0
     for (ix = 1; ix < a->used; ix++) {
4555
0
        *tmpc    = *tmpa++ - mu;
4556
0
        mu       = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
4557
0
        *tmpc++ &= MP_MASK;
4558
0
     }
4559
0
  }
4560
4561
  /* zero excess digits */
4562
0
  while (ix++ < oldused) {
4563
0
     *tmpc++ = 0;
4564
0
  }
4565
0
  mp_clamp(c);
4566
0
  return MP_OKAY;
4567
0
}
4568
4569
#endif /* defined(HAVE_ECC) || !defined(NO_PWDBASED) */
4570
4571
4572
#if defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) || defined(HAVE_ECC) || \
4573
    defined(DEBUG_WOLFSSL) || !defined(NO_RSA) || !defined(NO_DSA) || \
4574
    !defined(NO_DH) || defined(WC_MP_TO_RADIX)
4575
4576
static const int lnz[16] = {
4577
   4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
4578
};
4579
4580
/* Counts the number of lsbs which are zero before the first zero bit */
4581
int mp_cnt_lsb(mp_int *a)
4582
0
{
4583
0
    int x;
4584
0
    mp_digit q = 0, qq;
4585
4586
    /* easy out */
4587
0
    if (mp_iszero(a) == MP_YES) {
4588
0
        return 0;
4589
0
    }
4590
4591
    /* scan lower digits until non-zero */
4592
0
    for (x = 0; x < a->used && a->dp[x] == 0; x++) {}
4593
0
    if (a->dp)
4594
0
        q = a->dp[x];
4595
0
    x *= DIGIT_BIT;
4596
4597
    /* now scan this digit until a 1 is found */
4598
0
    if ((q & 1) == 0) {
4599
0
        do {
4600
0
            qq  = q & 15;
4601
0
            x  += lnz[qq];
4602
0
            q >>= 4;
4603
0
        } while (qq == 0);
4604
0
    }
4605
0
    return x;
4606
0
}
4607
4608
4609
4610
4611
static int s_is_power_of_two(mp_digit b, int *p)
4612
0
{
4613
0
   int x;
4614
4615
   /* fast return if no power of two */
4616
0
   if ((b==0) || (b & (b-1))) {
4617
0
      return 0;
4618
0
   }
4619
4620
0
   for (x = 0; x < DIGIT_BIT; x++) {
4621
0
      if (b == (((mp_digit)1)<<x)) {
4622
0
         *p = x;
4623
0
         return 1;
4624
0
      }
4625
0
   }
4626
0
   return 0;
4627
0
}
4628
4629
/* single digit division (based on routine from MPI) */
4630
static int mp_div_d (mp_int * a, mp_digit b, mp_int * c, mp_digit * d)
4631
0
{
4632
0
  mp_int  q;
4633
0
  mp_word w;
4634
0
  mp_digit t;
4635
0
  int     res = MP_OKAY, ix;
4636
4637
  /* cannot divide by zero */
4638
0
  if (b == 0) {
4639
0
     return MP_VAL;
4640
0
  }
4641
4642
  /* quick outs */
4643
0
  if (b == 1 || mp_iszero(a) == MP_YES) {
4644
0
     if (d != NULL) {
4645
0
        *d = 0;
4646
0
     }
4647
0
     if (c != NULL) {
4648
0
        return mp_copy(a, c);
4649
0
     }
4650
0
     return MP_OKAY;
4651
0
  }
4652
4653
  /* power of two ? */
4654
0
  if (s_is_power_of_two(b, &ix) == 1) {
4655
0
     if (d != NULL) {
4656
0
        *d = a->dp[0] & ((((mp_digit)1)<<ix) - 1);
4657
0
     }
4658
0
     if (c != NULL) {
4659
0
        return mp_div_2d(a, ix, c, NULL);
4660
0
     }
4661
0
     return MP_OKAY;
4662
0
  }
4663
4664
0
#ifdef BN_MP_DIV_3_C
4665
  /* three? */
4666
0
  if (b == 3) {
4667
0
     return mp_div_3(a, c, d);
4668
0
  }
4669
0
#endif
4670
4671
  /* no easy answer [c'est la vie].  Just division */
4672
0
  if (c != NULL) {
4673
0
      if ((res = mp_init_size(&q, a->used)) != MP_OKAY) {
4674
0
         return res;
4675
0
      }
4676
4677
0
      q.used = a->used;
4678
0
      q.sign = a->sign;
4679
0
  }
4680
0
  else {
4681
0
      if ((res = mp_init(&q)) != MP_OKAY) {
4682
0
         return res;
4683
0
      }
4684
0
  }
4685
4686
0
  w = 0;
4687
4688
0
  if (a->used == 0)
4689
0
      return MP_VAL;
4690
4691
0
  for (ix = a->used - 1; ix >= 0; ix--) {
4692
0
     w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]);
4693
4694
0
     if (w >= b) {
4695
#ifdef WOLFSSL_LINUXKM
4696
        t = (mp_digit)w;
4697
        /* Linux kernel macro for in-place 64 bit integer division. */
4698
        do_div(t, b);
4699
#else
4700
0
        t = (mp_digit)(w / b);
4701
0
#endif
4702
0
        w -= ((mp_word)t) * ((mp_word)b);
4703
0
      } else {
4704
0
        t = 0;
4705
0
      }
4706
0
      if (c != NULL)
4707
0
        q.dp[ix] = (mp_digit)t;
4708
0
  }
4709
4710
0
  if (d != NULL) {
4711
0
     *d = (mp_digit)w;
4712
0
  }
4713
4714
0
  if (c != NULL) {
4715
0
     mp_clamp(&q);
4716
0
     mp_exch(&q, c);
4717
0
  }
4718
0
  mp_clear(&q);
4719
4720
0
  return res;
4721
0
}
4722
4723
4724
int mp_mod_d (mp_int * a, mp_digit b, mp_digit * c)
4725
0
{
4726
0
  return mp_div_d(a, b, NULL, c);
4727
0
}
4728
4729
#endif /* WOLFSSL_KEY_GEN || HAVE_COMP_KEY || HAVE_ECC || DEBUG_WOLFSSL */
4730
4731
#if (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)) || !defined(NO_DH) || !defined(NO_DSA)
4732
4733
const FLASH_QUALIFIER mp_digit ltm_prime_tab[PRIME_SIZE] = {
4734
  0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013,
4735
  0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035,
4736
  0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059,
4737
  0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F,
4738
#ifndef MP_8BIT
4739
  0x0083,
4740
  0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD,
4741
  0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF,
4742
  0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107,
4743
  0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137,
4744
4745
  0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167,
4746
  0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199,
4747
  0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9,
4748
  0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7,
4749
  0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239,
4750
  0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265,
4751
  0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293,
4752
  0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF,
4753
4754
  0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301,
4755
  0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B,
4756
  0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371,
4757
  0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD,
4758
  0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5,
4759
  0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419,
4760
  0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449,
4761
  0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B,
4762
4763
  0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7,
4764
  0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503,
4765
  0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529,
4766
  0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F,
4767
  0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3,
4768
  0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7,
4769
  0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623,
4770
  0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653
4771
#endif
4772
};
4773
4774
4775
/* Miller-Rabin test of "a" to the base of "b" as described in
4776
 * HAC pp. 139 Algorithm 4.24
4777
 *
4778
 * Sets result to 0 if definitely composite or 1 if probably prime.
4779
 * Randomly the chance of error is no more than 1/4 and often
4780
 * very much lower.
4781
 */
4782
static int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result)
4783
0
{
4784
0
  mp_int  n1, y, r;
4785
0
  int     s, j, err;
4786
4787
  /* default */
4788
0
  *result = MP_NO;
4789
4790
  /* ensure b > 1 */
4791
0
  if (mp_cmp_d(b, 1) != MP_GT) {
4792
0
     return MP_VAL;
4793
0
  }
4794
4795
  /* get n1 = a - 1 */
4796
0
  if ((err = mp_init_copy (&n1, a)) != MP_OKAY) {
4797
0
    return err;
4798
0
  }
4799
0
  if ((err = mp_sub_d (&n1, 1, &n1)) != MP_OKAY) {
4800
0
    goto LBL_N1;
4801
0
  }
4802
4803
  /* set 2**s * r = n1 */
4804
0
  if ((err = mp_init_copy (&r, &n1)) != MP_OKAY) {
4805
0
    goto LBL_N1;
4806
0
  }
4807
4808
  /* count the number of least significant bits
4809
   * which are zero
4810
   */
4811
0
  s = mp_cnt_lsb(&r);
4812
4813
  /* now divide n - 1 by 2**s */
4814
0
  if ((err = mp_div_2d (&r, s, &r, NULL)) != MP_OKAY) {
4815
0
    goto LBL_R;
4816
0
  }
4817
4818
  /* compute y = b**r mod a */
4819
0
  if ((err = mp_init (&y)) != MP_OKAY) {
4820
0
    goto LBL_R;
4821
0
  }
4822
#if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH)
4823
#ifndef WOLFSSL_SP_NO_2048
4824
  if (mp_count_bits(a) == 1024 && mp_isodd(a))
4825
      err = sp_ModExp_1024(b, &r, a, &y);
4826
  else if (mp_count_bits(a) == 2048 && mp_isodd(a))
4827
      err = sp_ModExp_2048(b, &r, a, &y);
4828
  else
4829
#endif
4830
#ifndef WOLFSSL_SP_NO_3072
4831
  if (mp_count_bits(a) == 1536 && mp_isodd(a))
4832
      err = sp_ModExp_1536(b, &r, a, &y);
4833
  else if (mp_count_bits(a) == 3072 && mp_isodd(a))
4834
      err = sp_ModExp_3072(b, &r, a, &y);
4835
  else
4836
#endif
4837
#ifdef WOLFSSL_SP_4096
4838
  if (mp_count_bits(a) == 4096 && mp_isodd(a))
4839
      err = sp_ModExp_4096(b, &r, a, &y);
4840
  else
4841
#endif
4842
#endif
4843
0
      err = mp_exptmod (b, &r, a, &y);
4844
0
  if (err != MP_OKAY)
4845
0
      goto LBL_Y;
4846
4847
  /* if y != 1 and y != n1 do */
4848
0
  if (mp_cmp_d (&y, 1) != MP_EQ && mp_cmp (&y, &n1) != MP_EQ) {
4849
0
    j = 1;
4850
    /* while j <= s-1 and y != n1 */
4851
0
    while ((j <= (s - 1)) && mp_cmp (&y, &n1) != MP_EQ) {
4852
0
      if ((err = mp_sqrmod (&y, a, &y)) != MP_OKAY) {
4853
0
         goto LBL_Y;
4854
0
      }
4855
4856
      /* if y == 1 then composite */
4857
0
      if (mp_cmp_d (&y, 1) == MP_EQ) {
4858
0
         goto LBL_Y;
4859
0
      }
4860
4861
0
      ++j;
4862
0
    }
4863
4864
    /* if y != n1 then composite */
4865
0
    if (mp_cmp (&y, &n1) != MP_EQ) {
4866
0
      goto LBL_Y;
4867
0
    }
4868
0
  }
4869
4870
  /* probably prime now */
4871
0
  *result = MP_YES;
4872
0
LBL_Y:mp_clear (&y);
4873
0
LBL_R:mp_clear (&r);
4874
0
LBL_N1:mp_clear (&n1);
4875
0
  return err;
4876
0
}
4877
4878
4879
/* determines if an integers is divisible by one
4880
 * of the first PRIME_SIZE primes or not
4881
 *
4882
 * sets result to 0 if not, 1 if yes
4883
 */
4884
static int mp_prime_is_divisible (mp_int * a, int *result)
4885
0
{
4886
0
  int     err, ix;
4887
0
  mp_digit res;
4888
4889
  /* default to not */
4890
0
  *result = MP_NO;
4891
4892
0
  for (ix = 0; ix < PRIME_SIZE; ix++) {
4893
    /* what is a mod LBL_prime_tab[ix] */
4894
0
    if ((err = mp_mod_d (a, ltm_prime_tab[ix], &res)) != MP_OKAY) {
4895
0
      return err;
4896
0
    }
4897
4898
    /* is the residue zero? */
4899
0
    if (res == 0) {
4900
0
      *result = MP_YES;
4901
0
      return MP_OKAY;
4902
0
    }
4903
0
  }
4904
4905
0
  return MP_OKAY;
4906
0
}
4907
4908
/*
4909
 * Sets result to 1 if probably prime, 0 otherwise
4910
 */
4911
int mp_prime_is_prime (mp_int * a, int t, int *result)
4912
0
{
4913
0
  mp_int  b;
4914
0
  int     ix, err, res;
4915
4916
  /* default to no */
4917
0
  *result = MP_NO;
4918
4919
  /* valid value of t? */
4920
0
  if (t <= 0 || t > PRIME_SIZE) {
4921
0
    return MP_VAL;
4922
0
  }
4923
4924
0
  if (mp_isone(a)) {
4925
0
      *result = MP_NO;
4926
0
      return MP_OKAY;
4927
0
  }
4928
4929
  /* is the input equal to one of the primes in the table? */
4930
0
  for (ix = 0; ix < PRIME_SIZE; ix++) {
4931
0
      if (mp_cmp_d(a, ltm_prime_tab[ix]) == MP_EQ) {
4932
0
         *result = MP_YES;
4933
0
         return MP_OKAY;
4934
0
      }
4935
0
  }
4936
4937
  /* first perform trial division */
4938
0
  if ((err = mp_prime_is_divisible (a, &res)) != MP_OKAY) {
4939
0
    return err;
4940
0
  }
4941
4942
  /* return if it was trivially divisible */
4943
0
  if (res == MP_YES) {
4944
0
    return MP_OKAY;
4945
0
  }
4946
4947
  /* now perform the miller-rabin rounds */
4948
0
  if ((err = mp_init (&b)) != MP_OKAY) {
4949
0
    return err;
4950
0
  }
4951
4952
0
  for (ix = 0; ix < t; ix++) {
4953
    /* set the prime */
4954
0
    if ((err = mp_set (&b, ltm_prime_tab[ix])) != MP_OKAY) {
4955
0
        goto LBL_B;
4956
0
    }
4957
4958
0
    if ((err = mp_prime_miller_rabin (a, &b, &res)) != MP_OKAY) {
4959
0
      goto LBL_B;
4960
0
    }
4961
4962
0
    if (res == MP_NO) {
4963
0
      goto LBL_B;
4964
0
    }
4965
0
  }
4966
4967
  /* passed the test */
4968
0
  *result = MP_YES;
4969
0
LBL_B:mp_clear (&b);
4970
0
  return err;
4971
0
}
4972
4973
4974
/*
4975
 * Sets result to 1 if probably prime, 0 otherwise
4976
 */
4977
int mp_prime_is_prime_ex (mp_int * a, int t, int *result, WC_RNG *rng)
4978
0
{
4979
0
  mp_int  b, c;
4980
0
  int     ix, err, res;
4981
0
  byte*   base = NULL;
4982
0
  word32  bitSz = 0;
4983
0
  word32  baseSz = 0;
4984
4985
  /* default to no */
4986
0
  *result = MP_NO;
4987
4988
  /* valid value of t? */
4989
0
  if (t <= 0 || t > PRIME_SIZE) {
4990
0
    return MP_VAL;
4991
0
  }
4992
4993
0
  if (a->sign == MP_NEG) {
4994
0
    return MP_VAL;
4995
0
  }
4996
4997
0
  if (mp_isone(a)) {
4998
0
    *result = MP_NO;
4999
0
    return MP_OKAY;
5000
0
  }
5001
5002
  /* is the input equal to one of the primes in the table? */
5003
0
  for (ix = 0; ix < PRIME_SIZE; ix++) {
5004
0
      if (mp_cmp_d(a, ltm_prime_tab[ix]) == MP_EQ) {
5005
0
         *result = MP_YES;
5006
0
         return MP_OKAY;
5007
0
      }
5008
0
  }
5009
5010
  /* first perform trial division */
5011
0
  if ((err = mp_prime_is_divisible (a, &res)) != MP_OKAY) {
5012
0
    return err;
5013
0
  }
5014
5015
  /* return if it was trivially divisible */
5016
0
  if (res == MP_YES) {
5017
0
    return MP_OKAY;
5018
0
  }
5019
5020
  /* now perform the miller-rabin rounds */
5021
0
  if ((err = mp_init (&b)) != MP_OKAY) {
5022
0
    return err;
5023
0
  }
5024
0
  if ((err = mp_init (&c)) != MP_OKAY) {
5025
0
      mp_clear(&b);
5026
0
    return err;
5027
0
  }
5028
5029
0
  bitSz = mp_count_bits(a);
5030
0
  baseSz = (bitSz / 8) + ((bitSz % 8) ? 1 : 0);
5031
0
  bitSz %= 8;
5032
5033
0
  base = (byte*)XMALLOC(baseSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5034
0
  if (base == NULL) {
5035
0
      err = MP_MEM;
5036
0
      goto LBL_B;
5037
0
  }
5038
5039
0
  if ((err = mp_sub_d(a, 2, &c)) != MP_OKAY) {
5040
0
      goto LBL_B;
5041
0
  }
5042
5043
 /* now do a miller rabin with up to t random numbers, this should
5044
  * give a (1/4)^t chance of a false prime. */
5045
0
  for (ix = 0; ix < t; ix++) {
5046
    /* Set a test candidate. */
5047
0
    if ((err = wc_RNG_GenerateBlock(rng, base, baseSz)) != 0) {
5048
0
        goto LBL_B;
5049
0
    }
5050
5051
    /* Clear bits higher than those in a. */
5052
0
    if (bitSz > 0) {
5053
0
        base[0] &= (1 << bitSz) - 1;
5054
0
    }
5055
5056
0
    if ((err = mp_read_unsigned_bin(&b, base, baseSz)) != MP_OKAY) {
5057
0
        goto LBL_B;
5058
0
    }
5059
5060
0
    if (mp_cmp_d(&b, 2) != MP_GT || mp_cmp(&b, &c) != MP_LT) {
5061
0
        ix--;
5062
0
        continue;
5063
0
    }
5064
5065
0
    if ((err = mp_prime_miller_rabin (a, &b, &res)) != MP_OKAY) {
5066
0
      goto LBL_B;
5067
0
    }
5068
5069
0
    if (res == MP_NO) {
5070
0
      goto LBL_B;
5071
0
    }
5072
0
  }
5073
5074
  /* passed the test */
5075
0
  *result = MP_YES;
5076
0
LBL_B:mp_clear (&b);
5077
0
      mp_clear (&c);
5078
0
      XFREE(base, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5079
0
  return err;
5080
0
}
5081
5082
#endif /* (WOLFSSL_KEY_GEN && !NO_RSA) || !NO_DH || !NO_DSA */
5083
5084
#if defined(WOLFSSL_KEY_GEN) && (!defined(NO_DH) || !defined(NO_DSA))
5085
5086
static const int USE_BBS = 1;
5087
5088
int mp_rand_prime(mp_int* a, int len, WC_RNG* rng, void* heap)
5089
0
{
5090
0
    int   err, res, type;
5091
0
    byte* buf;
5092
5093
0
    if (a == NULL || rng == NULL)
5094
0
        return MP_VAL;
5095
5096
    /* get type */
5097
0
    if (len < 0) {
5098
0
        type = USE_BBS;
5099
0
        len = -len;
5100
0
    } else {
5101
0
        type = 0;
5102
0
    }
5103
5104
    /* allow sizes between 2 and 512 bytes for a prime size */
5105
0
    if (len < 2 || len > 512) {
5106
0
        return MP_VAL;
5107
0
    }
5108
5109
    /* allocate buffer to work with */
5110
0
    buf = (byte*)XMALLOC(len, heap, DYNAMIC_TYPE_RSA);
5111
0
    if (buf == NULL) {
5112
0
        return MP_MEM;
5113
0
    }
5114
0
    XMEMSET(buf, 0, len);
5115
5116
0
    do {
5117
#ifdef SHOW_GEN
5118
        printf(".");
5119
        fflush(stdout);
5120
#endif
5121
        /* generate value */
5122
0
        err = wc_RNG_GenerateBlock(rng, buf, len);
5123
0
        if (err != 0) {
5124
0
            XFREE(buf, heap, DYNAMIC_TYPE_RSA);
5125
0
            return err;
5126
0
        }
5127
5128
        /* munge bits */
5129
0
        buf[0]     |= 0x80 | 0x40;
5130
0
        buf[len-1] |= 0x01 | ((type & USE_BBS) ? 0x02 : 0x00);
5131
5132
        /* load value */
5133
0
        if ((err = mp_read_unsigned_bin(a, buf, len)) != MP_OKAY) {
5134
0
            XFREE(buf, heap, DYNAMIC_TYPE_RSA);
5135
0
            return err;
5136
0
        }
5137
5138
        /* test */
5139
        /* Running Miller-Rabin up to 3 times gives us a 2^{-80} chance
5140
         * of a 1024-bit candidate being a false positive, when it is our
5141
         * prime candidate. (Note 4.49 of Handbook of Applied Cryptography.)
5142
         * Using 8 because we've always used 8. */
5143
0
        if ((err = mp_prime_is_prime_ex(a, 8, &res, rng)) != MP_OKAY) {
5144
0
            XFREE(buf, heap, DYNAMIC_TYPE_RSA);
5145
0
            return err;
5146
0
        }
5147
0
    } while (res == MP_NO);
5148
5149
0
    XMEMSET(buf, 0, len);
5150
0
    XFREE(buf, heap, DYNAMIC_TYPE_RSA);
5151
5152
0
    return MP_OKAY;
5153
0
}
5154
5155
#endif
5156
5157
#if defined(WOLFSSL_KEY_GEN)
5158
5159
/* computes least common multiple as |a*b|/(a, b) */
5160
int mp_lcm (mp_int * a, mp_int * b, mp_int * c)
5161
0
{
5162
0
  int     res;
5163
0
  mp_int  t1, t2;
5164
5165
  /* LCM of 0 and any number is undefined as 0 is not in the set of values
5166
   * being used. */
5167
0
  if (mp_iszero (a) == MP_YES || mp_iszero (b) == MP_YES) {
5168
0
    return MP_VAL;
5169
0
  }
5170
5171
0
  if ((res = mp_init_multi (&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
5172
0
    return res;
5173
0
  }
5174
5175
  /* t1 = get the GCD of the two inputs */
5176
0
  if ((res = mp_gcd (a, b, &t1)) != MP_OKAY) {
5177
0
    goto LBL_T;
5178
0
  }
5179
5180
  /* divide the smallest by the GCD */
5181
0
  if (mp_cmp_mag(a, b) == MP_LT) {
5182
     /* store quotient in t2 such that t2 * b is the LCM */
5183
0
     if ((res = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) {
5184
0
        goto LBL_T;
5185
0
     }
5186
0
     res = mp_mul(b, &t2, c);
5187
0
  } else {
5188
     /* store quotient in t2 such that t2 * a is the LCM */
5189
0
     if ((res = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) {
5190
0
        goto LBL_T;
5191
0
     }
5192
0
     res = mp_mul(a, &t2, c);
5193
0
  }
5194
5195
  /* fix the sign to positive */
5196
0
  c->sign = MP_ZPOS;
5197
5198
0
LBL_T:
5199
0
  mp_clear(&t1);
5200
0
  mp_clear(&t2);
5201
0
  return res;
5202
0
}
5203
5204
5205
5206
/* Greatest Common Divisor using the binary method */
5207
int mp_gcd (mp_int * a, mp_int * b, mp_int * c)
5208
0
{
5209
0
    mp_int  u, v;
5210
0
    int     k, u_lsb, v_lsb, res;
5211
5212
    /* either zero than gcd is the largest */
5213
0
    if (mp_iszero (a) == MP_YES) {
5214
        /* GCD of 0 and 0 is undefined as all integers divide 0. */
5215
0
        if (mp_iszero (b) == MP_YES) {
5216
0
           return MP_VAL;
5217
0
        }
5218
0
        return mp_abs (b, c);
5219
0
    }
5220
0
    if (mp_iszero (b) == MP_YES) {
5221
0
        return mp_abs (a, c);
5222
0
    }
5223
5224
    /* get copies of a and b we can modify */
5225
0
    if ((res = mp_init_copy (&u, a)) != MP_OKAY) {
5226
0
        return res;
5227
0
    }
5228
5229
0
    if ((res = mp_init_copy (&v, b)) != MP_OKAY) {
5230
0
        goto LBL_U;
5231
0
    }
5232
5233
    /* must be positive for the remainder of the algorithm */
5234
0
    u.sign = v.sign = MP_ZPOS;
5235
5236
    /* B1.  Find the common power of two for u and v */
5237
0
    u_lsb = mp_cnt_lsb(&u);
5238
0
    v_lsb = mp_cnt_lsb(&v);
5239
0
    k     = MIN(u_lsb, v_lsb);
5240
5241
0
    if (k > 0) {
5242
        /* divide the power of two out */
5243
0
        if ((res = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) {
5244
0
            goto LBL_V;
5245
0
        }
5246
5247
0
        if ((res = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) {
5248
0
            goto LBL_V;
5249
0
        }
5250
0
    }
5251
5252
    /* divide any remaining factors of two out */
5253
0
    if (u_lsb != k) {
5254
0
        if ((res = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) {
5255
0
            goto LBL_V;
5256
0
        }
5257
0
    }
5258
5259
0
    if (v_lsb != k) {
5260
0
        if ((res = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) {
5261
0
            goto LBL_V;
5262
0
        }
5263
0
    }
5264
5265
0
    while (mp_iszero(&v) == MP_NO) {
5266
        /* make sure v is the largest */
5267
0
        if (mp_cmp_mag(&u, &v) == MP_GT) {
5268
            /* swap u and v to make sure v is >= u */
5269
0
            mp_exch(&u, &v);
5270
0
        }
5271
5272
        /* subtract smallest from largest */
5273
0
        if ((res = s_mp_sub(&v, &u, &v)) != MP_OKAY) {
5274
0
            goto LBL_V;
5275
0
        }
5276
5277
        /* Divide out all factors of two */
5278
0
        if ((res = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) {
5279
0
            goto LBL_V;
5280
0
        }
5281
0
    }
5282
5283
    /* multiply by 2**k which we divided out at the beginning */
5284
0
    if ((res = mp_mul_2d (&u, k, c)) != MP_OKAY) {
5285
0
        goto LBL_V;
5286
0
    }
5287
0
    c->sign = MP_ZPOS;
5288
0
    res = MP_OKAY;
5289
0
LBL_V:mp_clear (&v);
5290
0
LBL_U:mp_clear (&u);
5291
0
    return res;
5292
0
}
5293
5294
#endif /* WOLFSSL_KEY_GEN */
5295
5296
5297
#if !defined(NO_DSA) || defined(HAVE_ECC) || defined(WOLFSSL_KEY_GEN) || \
5298
    defined(HAVE_COMP_KEY) || defined(WOLFSSL_DEBUG_MATH) || \
5299
    defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA) || defined(WC_MP_TO_RADIX)
5300
5301
/* chars used in radix conversions */
5302
const char *mp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
5303
                        "abcdefghijklmnopqrstuvwxyz+/";
5304
#endif
5305
5306
#if !defined(NO_DSA) || defined(HAVE_ECC) || defined(OPENSSL_EXTRA)
5307
/* read a string [ASCII] in a given radix */
5308
int mp_read_radix (mp_int * a, const char *str, int radix)
5309
0
{
5310
0
  int     y, res, neg;
5311
0
  char    ch;
5312
5313
  /* zero the digit bignum */
5314
0
  mp_zero(a);
5315
5316
  /* make sure the radix is ok */
5317
0
  if (radix < MP_RADIX_BIN || radix > MP_RADIX_MAX) {
5318
0
    return MP_VAL;
5319
0
  }
5320
5321
  /* if the leading digit is a
5322
   * minus set the sign to negative.
5323
   */
5324
0
  if (*str == '-') {
5325
0
    ++str;
5326
0
    neg = MP_NEG;
5327
0
  } else {
5328
0
    neg = MP_ZPOS;
5329
0
  }
5330
5331
  /* set the integer to the default of zero */
5332
0
  mp_zero (a);
5333
5334
  /* process each digit of the string */
5335
0
  while (*str != '\0') {
5336
    /* if the radix <= 36 the conversion is case insensitive
5337
     * this allows numbers like 1AB and 1ab to represent the same  value
5338
     * [e.g. in hex]
5339
     */
5340
0
    ch = (radix <= 36) ? (char)XTOUPPER((unsigned char)*str) : *str;
5341
0
    for (y = 0; y < 64; y++) {
5342
0
      if (ch == mp_s_rmap[y]) {
5343
0
         break;
5344
0
      }
5345
0
    }
5346
5347
    /* if the char was found in the map
5348
     * and is less than the given radix add it
5349
     * to the number, otherwise exit the loop.
5350
     */
5351
0
    if (y < radix) {
5352
0
      if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) {
5353
0
         mp_zero(a);
5354
0
         return res;
5355
0
      }
5356
0
      if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) {
5357
0
         mp_zero(a);
5358
0
         return res;
5359
0
      }
5360
0
    } else {
5361
0
      break;
5362
0
    }
5363
0
    ++str;
5364
0
  }
5365
5366
  /* Skip whitespace at end of str */
5367
0
  while (CharIsWhiteSpace(*str))
5368
0
    ++str;
5369
  /* if digit in isn't null term, then invalid character was found */
5370
0
  if (*str != '\0') {
5371
0
     mp_zero (a);
5372
0
     return MP_VAL;
5373
0
  }
5374
5375
  /* set the sign only if a != 0 */
5376
0
  if (mp_iszero(a) != MP_YES) {
5377
0
     a->sign = neg;
5378
0
  }
5379
0
  return MP_OKAY;
5380
0
}
5381
#endif /* !defined(NO_DSA) || defined(HAVE_ECC) */
5382
5383
#ifdef WC_MP_TO_RADIX
5384
5385
/* returns size of ASCII representation */
5386
int mp_radix_size (mp_int *a, int radix, int *size)
5387
0
{
5388
0
    int     res, digs;
5389
0
    mp_int  t;
5390
0
    mp_digit d;
5391
5392
0
    *size = 0;
5393
5394
    /* special case for binary */
5395
0
    if (radix == MP_RADIX_BIN) {
5396
0
        *size = mp_count_bits(a);
5397
0
        if (*size == 0)
5398
0
          *size = 1;
5399
0
        *size += (a->sign == MP_NEG ? 1 : 0) + 1; /* "-" sign + null term */
5400
0
        return MP_OKAY;
5401
0
    }
5402
5403
    /* make sure the radix is in range */
5404
0
    if (radix < MP_RADIX_BIN || radix > MP_RADIX_MAX) {
5405
0
        return MP_VAL;
5406
0
    }
5407
5408
0
    if (mp_iszero(a) == MP_YES) {
5409
0
#ifndef WC_DISABLE_RADIX_ZERO_PAD
5410
0
        if (radix == 16)
5411
0
            *size = 3;
5412
0
        else
5413
0
#endif
5414
0
            *size = 2;
5415
0
        return MP_OKAY;
5416
0
    }
5417
5418
    /* digs is the digit count */
5419
0
    digs = 0;
5420
5421
    /* init a copy of the input */
5422
0
    if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
5423
0
        return res;
5424
0
    }
5425
5426
    /* force temp to positive */
5427
0
    t.sign = MP_ZPOS;
5428
5429
    /* fetch out all of the digits */
5430
0
    while (mp_iszero (&t) == MP_NO) {
5431
0
        if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
5432
0
            mp_clear (&t);
5433
0
            return res;
5434
0
        }
5435
0
        ++digs;
5436
0
    }
5437
0
    mp_clear (&t);
5438
5439
0
#ifndef WC_DISABLE_RADIX_ZERO_PAD
5440
    /* For hexadecimal output, add zero padding when number of digits is odd */
5441
0
    if ((digs & 1) && (radix == 16)) {
5442
0
        ++digs;
5443
0
    }
5444
0
#endif
5445
5446
    /* if it's negative add one for the sign */
5447
0
    if (a->sign == MP_NEG) {
5448
0
        ++digs;
5449
0
    }
5450
5451
    /* return digs + 1, the 1 is for the NULL byte that would be required. */
5452
0
    *size = digs + 1;
5453
0
    return MP_OKAY;
5454
0
}
5455
5456
/* stores a bignum as a ASCII string in a given radix (2..64) */
5457
int mp_toradix (mp_int *a, char *str, int radix)
5458
0
{
5459
0
    int     res, digs;
5460
0
    mp_int  t;
5461
0
    mp_digit d;
5462
0
    char   *_s = str;
5463
5464
    /* check range of the radix */
5465
0
    if (radix < MP_RADIX_BIN || radix > MP_RADIX_MAX) {
5466
0
        return MP_VAL;
5467
0
    }
5468
5469
    /* quick out if its zero */
5470
0
    if (mp_iszero(a) == MP_YES) {
5471
0
#ifndef WC_DISABLE_RADIX_ZERO_PAD
5472
0
        if (radix == 16) {
5473
0
            *str++ = '0';
5474
0
        }
5475
0
#endif
5476
0
        *str++ = '0';
5477
0
        *str = '\0';
5478
0
        return MP_OKAY;
5479
0
    }
5480
5481
0
    if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
5482
0
        return res;
5483
0
    }
5484
5485
    /* if it is negative output a - */
5486
0
    if (t.sign == MP_NEG) {
5487
0
        ++_s;
5488
0
        *str++ = '-';
5489
0
        t.sign = MP_ZPOS;
5490
0
    }
5491
5492
0
    digs = 0;
5493
0
    while (mp_iszero (&t) == MP_NO) {
5494
0
        if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
5495
0
            mp_clear (&t);
5496
0
            return res;
5497
0
        }
5498
0
        *str++ = mp_s_rmap[d];
5499
0
        ++digs;
5500
0
    }
5501
0
#ifndef WC_DISABLE_RADIX_ZERO_PAD
5502
    /* For hexadecimal output, add zero padding when number of digits is odd */
5503
0
    if ((digs & 1) && (radix == 16)) {
5504
0
        *str++ = mp_s_rmap[0];
5505
0
        ++digs;
5506
0
    }
5507
0
#endif
5508
    /* reverse the digits of the string.  In this case _s points
5509
     * to the first digit [excluding the sign] of the number]
5510
     */
5511
0
    bn_reverse ((unsigned char *)_s, digs);
5512
5513
    /* append a NULL so the string is properly terminated */
5514
0
    *str = '\0';
5515
5516
0
    mp_clear (&t);
5517
0
    return MP_OKAY;
5518
0
}
5519
5520
#ifdef WOLFSSL_DEBUG_MATH
5521
void mp_dump(const char* desc, mp_int* a, byte verbose)
5522
{
5523
  char *buffer;
5524
  int size = a->alloc;
5525
5526
  buffer = (char*)XMALLOC(size * sizeof(mp_digit) * 2, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5527
  if (buffer == NULL) {
5528
    return;
5529
  }
5530
5531
  printf("%s: ptr=%p, used=%d, sign=%d, size=%d, mpd=%d\n",
5532
    desc, a, a->used, a->sign, size, (int)sizeof(mp_digit));
5533
5534
  mp_tohex(a, buffer);
5535
  printf("  %s\n  ", buffer);
5536
5537
  if (verbose) {
5538
    int i;
5539
    for(i=0; i<a->alloc * (int)sizeof(mp_digit); i++) {
5540
      printf("%02x ", *(((byte*)a->dp) + i));
5541
    }
5542
    printf("\n");
5543
  }
5544
5545
  XFREE(buffer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
5546
}
5547
#endif /* WOLFSSL_DEBUG_MATH */
5548
5549
#endif /* WC_MP_TO_RADIX */
5550
5551
#endif /* WOLFSSL_SP_MATH */
5552
5553
#endif /* !USE_FAST_MATH && USE_INTEGER_HEAP_MATH */
5554
5555
#endif /* NO_BIG_INT */