1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
|
/*
* Number Theory Functions
* (C) 1999-2011,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/numthry.h>
#include <botan/reducer.h>
#include <botan/internal/bit_ops.h>
#include <botan/internal/mp_core.h>
#include <botan/internal/ct_utils.h>
#include <algorithm>
namespace Botan {
/*
* Return the number of 0 bits at the end of n
*/
size_t low_zero_bits(const BigInt& n)
{
size_t low_zero = 0;
if(n.is_positive() && n.is_nonzero())
{
for(size_t i = 0; i != n.size(); ++i)
{
const word x = n.word_at(i);
if(x)
{
low_zero += ctz(x);
break;
}
else
low_zero += BOTAN_MP_WORD_BITS;
}
}
return low_zero;
}
/*
* Calculate the GCD
*/
BigInt gcd(const BigInt& a, const BigInt& b)
{
if(a.is_zero() || b.is_zero()) return 0;
if(a == 1 || b == 1) return 1;
BigInt x = a, y = b;
x.set_sign(BigInt::Positive);
y.set_sign(BigInt::Positive);
size_t shift = std::min(low_zero_bits(x), low_zero_bits(y));
x >>= shift;
y >>= shift;
while(x.is_nonzero())
{
x >>= low_zero_bits(x);
y >>= low_zero_bits(y);
if(x >= y) { x -= y; x >>= 1; }
else { y -= x; y >>= 1; }
}
return (y << shift);
}
/*
* Calculate the LCM
*/
BigInt lcm(const BigInt& a, const BigInt& b)
{
return ((a * b) / gcd(a, b));
}
/*
Sets result to a^-1 * 2^k mod a
with n <= k <= 2n
Returns k
"The Montgomery Modular Inverse - Revisited" Çetin Koç, E. Savas
http://citeseerx.ist.psu.edu/viewdoc/citations?doi=10.1.1.75.8377
A const time implementation of this algorithm is described in
"Constant Time Modular Inversion" Joppe W. Bos
http://www.joppebos.com/files/CTInversion.pdf
*/
size_t almost_montgomery_inverse(BigInt& result,
const BigInt& a,
const BigInt& p)
{
size_t k = 0;
BigInt u = p, v = a, r = 0, s = 1;
while(v > 0)
{
if(u.is_even())
{
u >>= 1;
s <<= 1;
}
else if(v.is_even())
{
v >>= 1;
r <<= 1;
}
else if(u > v)
{
u -= v;
u >>= 1;
r += s;
s <<= 1;
}
else
{
v -= u;
v >>= 1;
s += r;
r <<= 1;
}
++k;
}
if(r >= p)
{
r = r - p;
}
result = p - r;
return k;
}
BigInt normalized_montgomery_inverse(const BigInt& a, const BigInt& p)
{
BigInt r;
size_t k = almost_montgomery_inverse(r, a, p);
for(size_t i = 0; i != k; ++i)
{
if(r.is_odd())
r += p;
r >>= 1;
}
return r;
}
BigInt ct_inverse_mod_odd_modulus(const BigInt& n, const BigInt& mod)
{
if(n.is_negative() || mod.is_negative())
throw Invalid_Argument("ct_inverse_mod_odd_modulus: arguments must be non-negative");
if(mod < 3 || mod.is_even())
throw Invalid_Argument("Bad modulus to ct_inverse_mod_odd_modulus");
/*
This uses a modular inversion algorithm designed by Niels Möller
and implemented in Nettle. The same algorithm was later also
adapted to GMP in mpn_sec_invert.
It can be easily implemented in a way that does not depend on
secret branches or memory lookups, providing resistance against
some forms of side channel attack.
There is also a description of the algorithm in Appendix 5 of "Fast
Software Polynomial Multiplication on ARM Processors using the NEON Engine"
by Danilo Câmara, Conrado P. L. Gouvêa, Julio López, and Ricardo
Dahab in LNCS 8182
http://conradoplg.cryptoland.net/files/2010/12/mocrysen13.pdf
Thanks to Niels for creating the algorithm, explaining some things
about it, and the reference to the paper.
*/
// todo allow this to be pre-calculated and passed in as arg
BigInt mp1o2 = (mod + 1) >> 1;
const size_t mod_words = mod.sig_words();
BOTAN_ASSERT(mod_words > 0, "Not empty");
BigInt a = n;
BigInt b = mod;
BigInt u = 1, v = 0;
a.grow_to(mod_words);
u.grow_to(mod_words);
v.grow_to(mod_words);
mp1o2.grow_to(mod_words);
secure_vector<word>& a_w = a.get_word_vector();
secure_vector<word>& b_w = b.get_word_vector();
secure_vector<word>& u_w = u.get_word_vector();
secure_vector<word>& v_w = v.get_word_vector();
CT::poison(a_w.data(), a_w.size());
CT::poison(b_w.data(), b_w.size());
CT::poison(u_w.data(), u_w.size());
CT::poison(v_w.data(), v_w.size());
// Only n.bits() + mod.bits() iterations are required, but avoid leaking the size of n
size_t bits = 2 * mod.bits();
while(bits--)
{
/*
const word odd = a.is_odd();
a -= odd * b;
const word underflow = a.is_negative();
b += a * underflow;
a.set_sign(BigInt::Positive);
a >>= 1;
if(underflow)
{
std::swap(u, v);
}
u -= odd * v;
u += u.is_negative() * mod;
const word odd_u = u.is_odd();
u >>= 1;
u += mp1o2 * odd_u;
*/
const word odd_a = a_w[0] & 1;
//if(odd_a) a -= b
word underflow = bigint_cnd_sub(odd_a, a_w.data(), b_w.data(), mod_words);
//if(underflow) { b -= a; a = abs(a); swap(u, v); }
bigint_cnd_add(underflow, b_w.data(), a_w.data(), mod_words);
bigint_cnd_abs(underflow, a_w.data(), mod_words);
bigint_cnd_swap(underflow, u_w.data(), v_w.data(), mod_words);
// a >>= 1
bigint_shr1(a_w.data(), mod_words, 0, 1);
//if(odd_a) u -= v;
word borrow = bigint_cnd_sub(odd_a, u_w.data(), v_w.data(), mod_words);
// if(borrow) u += p
bigint_cnd_add(borrow, u_w.data(), mod.data(), mod_words);
const word odd_u = u_w[0] & 1;
// u >>= 1
bigint_shr1(u_w.data(), mod_words, 0, 1);
//if(odd_u) u += mp1o2;
bigint_cnd_add(odd_u, u_w.data(), mp1o2.data(), mod_words);
}
CT::unpoison(a_w.data(), a_w.size());
CT::unpoison(b_w.data(), b_w.size());
CT::unpoison(u_w.data(), u_w.size());
CT::unpoison(v_w.data(), v_w.size());
BOTAN_ASSERT(a.is_zero(), "A is zero");
if(b != 1)
return 0;
return v;
}
/*
* Find the Modular Inverse
*/
BigInt inverse_mod(const BigInt& n, const BigInt& mod)
{
if(mod.is_zero())
throw BigInt::DivideByZero();
if(mod.is_negative() || n.is_negative())
throw Invalid_Argument("inverse_mod: arguments must be non-negative");
if(n.is_zero() || (n.is_even() && mod.is_even()))
return 0; // fast fail checks
if(mod.is_odd())
return ct_inverse_mod_odd_modulus(n, mod);
BigInt u = mod, v = n;
BigInt A = 1, B = 0, C = 0, D = 1;
while(u.is_nonzero())
{
const size_t u_zero_bits = low_zero_bits(u);
u >>= u_zero_bits;
for(size_t i = 0; i != u_zero_bits; ++i)
{
if(A.is_odd() || B.is_odd())
{ A += n; B -= mod; }
A >>= 1; B >>= 1;
}
const size_t v_zero_bits = low_zero_bits(v);
v >>= v_zero_bits;
for(size_t i = 0; i != v_zero_bits; ++i)
{
if(C.is_odd() || D.is_odd())
{ C += n; D -= mod; }
C >>= 1; D >>= 1;
}
if(u >= v) { u -= v; A -= C; B -= D; }
else { v -= u; C -= A; D -= B; }
}
if(v != 1)
return 0; // no modular inverse
while(D.is_negative()) D += mod;
while(D >= mod) D -= mod;
return D;
}
word monty_inverse(word input)
{
if(input == 0)
throw Exception("monty_inverse: divide by zero");
word b = input;
word x2 = 1, x1 = 0, y2 = 0, y1 = 1;
// First iteration, a = n+1
word q = bigint_divop(1, 0, b);
word r = (MP_WORD_MAX - q*b) + 1;
word x = x2 - q*x1;
word y = y2 - q*y1;
word a = b;
b = r;
x2 = x1;
x1 = x;
y2 = y1;
y1 = y;
while(b > 0)
{
q = a / b;
r = a - q*b;
x = x2 - q*x1;
y = y2 - q*y1;
a = b;
b = r;
x2 = x1;
x1 = x;
y2 = y1;
y1 = y;
}
// Now invert in addition space
y2 = (MP_WORD_MAX - y2) + 1;
return y2;
}
/*
* Modular Exponentiation
*/
BigInt power_mod(const BigInt& base, const BigInt& exp, const BigInt& mod)
{
Power_Mod pow_mod(mod);
/*
* Calling set_base before set_exponent means we end up using a
* minimal window. This makes sense given that here we know that any
* precomputation is wasted.
*/
pow_mod.set_base(base);
pow_mod.set_exponent(exp);
return pow_mod.execute();
}
namespace {
bool mr_witness(BigInt&& y,
const Modular_Reducer& reducer_n,
const BigInt& n_minus_1, size_t s)
{
if(y == 1 || y == n_minus_1)
return false;
for(size_t i = 1; i != s; ++i)
{
y = reducer_n.square(y);
if(y == 1) // found a non-trivial square root
return true;
if(y == n_minus_1) // -1, trivial square root, so give up
return false;
}
return true; // fails Fermat test
}
size_t mr_test_iterations(size_t n_bits, size_t prob, bool random)
{
const size_t base = (prob + 2) / 2; // worst case 4^-t error rate
/*
* For randomly chosen numbers we can use the estimates from
* http://www.math.dartmouth.edu/~carlp/PDF/paper88.pdf
*
* These values are derived from the inequality for p(k,t) given on
* the second page.
*/
if(random && prob <= 80)
{
if(n_bits >= 1536)
return 2; // < 2^-89
if(n_bits >= 1024)
return 4; // < 2^-89
if(n_bits >= 512)
return 5; // < 2^-80
if(n_bits >= 256)
return 11; // < 2^-80
}
return base;
}
}
/*
* Test for primaility using Miller-Rabin
*/
bool is_prime(const BigInt& n, RandomNumberGenerator& rng,
size_t prob, bool is_random)
{
if(n == 2)
return true;
if(n <= 1 || n.is_even())
return false;
// Fast path testing for small numbers (<= 65521)
if(n <= PRIMES[PRIME_TABLE_SIZE-1])
{
const u16bit num = static_cast<u16bit>(n.word_at(0));
return std::binary_search(PRIMES, PRIMES + PRIME_TABLE_SIZE, num);
}
const size_t test_iterations = mr_test_iterations(n.bits(), prob, is_random);
const BigInt n_minus_1 = n - 1;
const size_t s = low_zero_bits(n_minus_1);
Fixed_Exponent_Power_Mod pow_mod(n_minus_1 >> s, n);
Modular_Reducer reducer(n);
for(size_t i = 0; i != test_iterations; ++i)
{
const BigInt a = BigInt::random_integer(rng, 2, n_minus_1);
BigInt y = pow_mod(a);
if(mr_witness(std::move(y), reducer, n_minus_1, s))
return false;
}
return true;
}
}
|