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
|
/*
* Number Theory Functions
* (C) 1999-2011,2016,2018,2019 Jack Lloyd
* (C) 2007,2008 Falko Strenzke, FlexSecure GmbH
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/numthry.h>
#include <botan/reducer.h>
#include <botan/internal/monty.h>
#include <botan/internal/divide.h>
#include <botan/rng.h>
#include <botan/internal/ct_utils.h>
#include <botan/internal/mp_core.h>
#include <botan/internal/monty_exp.h>
#include <botan/internal/primality.h>
#include <algorithm>
namespace Botan {
namespace {
void sub_abs(BigInt& z, const BigInt& x, const BigInt& y)
{
const size_t x_sw = x.sig_words();
const size_t y_sw = y.sig_words();
z.resize(std::max(x_sw, y_sw));
bigint_sub_abs(z.mutable_data(),
x.data(), x_sw,
y.data(), y_sw);
}
}
/*
* Tonelli-Shanks algorithm
*/
BigInt ressol(const BigInt& a, const BigInt& p)
{
if(p <= 1 || p.is_even())
throw Invalid_Argument("ressol: invalid prime");
if(a == 0)
return 0;
else if(a < 0)
throw Invalid_Argument("ressol: value to solve for must be positive");
else if(a >= p)
throw Invalid_Argument("ressol: value to solve for must be less than p");
if(p == 2)
return a;
if(jacobi(a, p) != 1) // not a quadratic residue
return -BigInt(1);
if(p % 4 == 3) // The easy case
{
return power_mod(a, ((p+1) >> 2), p);
}
size_t s = low_zero_bits(p - 1);
BigInt q = p >> s;
q -= 1;
q >>= 1;
Modular_Reducer mod_p(p);
BigInt r = power_mod(a, q, p);
BigInt n = mod_p.multiply(a, mod_p.square(r));
r = mod_p.multiply(r, a);
if(n == 1)
return r;
// find random quadratic nonresidue z
word z = 2;
for(;;)
{
if(jacobi(z, p) == -1) // found one
break;
z += 1; // try next z
/*
* The expected number of tests to find a non-residue modulo a
* prime is 2. If we have not found one after 256 then almost
* certainly we have been given a non-prime p.
*/
if(z >= 256)
return -BigInt(1);
}
BigInt c = power_mod(z, (q << 1) + 1, p);
while(n > 1)
{
q = n;
size_t i = 0;
while(q != 1)
{
q = mod_p.square(q);
++i;
if(i >= s)
{
return -BigInt(1);
}
}
c = power_mod(c, BigInt::power_of_2(s-i-1), p);
r = mod_p.multiply(r, c);
c = mod_p.square(c);
n = mod_p.multiply(n, c);
s = i;
}
return r;
}
/*
* Calculate the Jacobi symbol
*/
int32_t jacobi(const BigInt& a, const BigInt& n)
{
if(n.is_even() || n < 2)
throw Invalid_Argument("jacobi: second argument must be odd and > 1");
BigInt x = a % n;
BigInt y = n;
int32_t J = 1;
while(y > 1)
{
x %= y;
if(x > y / 2)
{
x = y - x;
if(y % 4 == 3)
J = -J;
}
if(x.is_zero())
return 0;
size_t shifts = low_zero_bits(x);
x >>= shifts;
if(shifts % 2)
{
word y_mod_8 = y % 8;
if(y_mod_8 == 3 || y_mod_8 == 5)
J = -J;
}
if(x % 4 == 3 && y % 4 == 3)
J = -J;
std::swap(x, y);
}
return J;
}
/*
* Square a BigInt
*/
BigInt square(const BigInt& x)
{
BigInt z = x;
secure_vector<word> ws;
z.square(ws);
return z;
}
/*
* Return the number of 0 bits at the end of n
*/
size_t low_zero_bits(const BigInt& n)
{
size_t low_zero = 0;
auto seen_nonempty_word = CT::Mask<word>::cleared();
for(size_t i = 0; i != n.size(); ++i)
{
const word x = n.word_at(i);
// ctz(0) will return sizeof(word)
const size_t tz_x = ctz(x);
// if x > 0 we want to count tz_x in total but not any
// further words, so set the mask after the addition
low_zero += seen_nonempty_word.if_not_set_return(tz_x);
seen_nonempty_word |= CT::Mask<word>::expand(x);
}
// if we saw no words with x > 0 then n == 0 and the value we have
// computed is meaningless. Instead return 0 in that case.
return seen_nonempty_word.if_set_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;
// See https://gcd.cr.yp.to/safegcd-20190413.pdf fig 1.2
BigInt f = a;
BigInt g = b;
f.const_time_poison();
g.const_time_poison();
f.set_sign(BigInt::Positive);
g.set_sign(BigInt::Positive);
const size_t common2s = std::min(low_zero_bits(f), low_zero_bits(g));
CT::unpoison(common2s);
f >>= common2s;
g >>= common2s;
f.ct_cond_swap(f.is_even(), g);
int32_t delta = 1;
const size_t loop_cnt = 4 + 3*std::max(f.bits(), g.bits());
BigInt newg, t;
for(size_t i = 0; i != loop_cnt; ++i)
{
sub_abs(newg, f, g);
const bool need_swap = (g.is_odd() && delta > 0);
// if(need_swap) delta *= -1
delta *= CT::Mask<uint8_t>::expand(need_swap).select(0, 2) - 1;
f.ct_cond_swap(need_swap, g);
g.ct_cond_swap(need_swap, newg);
delta += 1;
g.ct_cond_add(g.is_odd(), f);
g >>= 1;
}
f <<= common2s;
f.const_time_unpoison();
g.const_time_unpoison();
return f;
}
/*
* Calculate the LCM
*/
BigInt lcm(const BigInt& a, const BigInt& b)
{
return ct_divide(a * b, gcd(a, b));
}
/*
* Modular Exponentiation
*/
BigInt power_mod(const BigInt& base, const BigInt& exp, const BigInt& mod)
{
if(mod.is_negative() || mod == 1)
{
return 0;
}
if(base.is_zero() || mod.is_zero())
{
if(exp.is_zero())
return 1;
return 0;
}
Modular_Reducer reduce_mod(mod);
const size_t exp_bits = exp.bits();
if(mod.is_odd())
{
const size_t powm_window = 4;
auto monty_mod = std::make_shared<Montgomery_Params>(mod, reduce_mod);
auto powm_base_mod = monty_precompute(monty_mod, reduce_mod.reduce(base), powm_window);
return monty_execute(*powm_base_mod, exp, exp_bits);
}
/*
Support for even modulus is just a convenience and not considered
cryptographically important, so this implementation is slow ...
*/
BigInt accum = 1;
BigInt g = reduce_mod.reduce(base);
BigInt t;
for(size_t i = 0; i != exp_bits; ++i)
{
t = reduce_mod.multiply(g, accum);
g = reduce_mod.square(g);
accum.ct_cond_assign(exp.get_bit(i), t);
}
return accum;
}
BigInt is_perfect_square(const BigInt& C)
{
if(C < 1)
throw Invalid_Argument("is_perfect_square requires C >= 1");
if(C == 1)
return 1;
const size_t n = C.bits();
const size_t m = (n + 1) / 2;
const BigInt B = C + BigInt::power_of_2(m);
BigInt X = BigInt::power_of_2(m) - 1;
BigInt X2 = (X*X);
for(;;)
{
X = (X2 + C) / (2*X);
X2 = (X*X);
if(X2 < B)
break;
}
if(X2 == C)
return X;
else
return 0;
}
/*
* Test for primality 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;
const size_t n_bits = n.bits();
// Fast path testing for small numbers (<= 65521)
if(n_bits <= 16)
{
const uint16_t num = static_cast<uint16_t>(n.word_at(0));
return std::binary_search(PRIMES, PRIMES + PRIME_TABLE_SIZE, num);
}
Modular_Reducer mod_n(n);
if(rng.is_seeded())
{
const size_t t = miller_rabin_test_iterations(n_bits, prob, is_random);
if(is_miller_rabin_probable_prime(n, mod_n, rng, t) == false)
return false;
if(is_random)
return true;
else
return is_lucas_probable_prime(n, mod_n);
}
else
{
return is_bailie_psw_probable_prime(n, mod_n);
}
}
}
|