| 1 |
#include <assert.h> |
| 2 |
#include "fe.h" |
| 3 |
#include "crypto_additions.h" |
| 4 |
|
| 5 |
/* sqrt(-1) */ |
| 6 |
static unsigned char i_bytes[32] = { |
| 7 |
0xb0, 0xa0, 0x0e, 0x4a, 0x27, 0x1b, 0xee, 0xc4, |
| 8 |
0x78, 0xe4, 0x2f, 0xad, 0x06, 0x18, 0x43, 0x2f, |
| 9 |
0xa7, 0xd7, 0xfb, 0x3d, 0x99, 0x00, 0x4d, 0x2b, |
| 10 |
0x0b, 0xdf, 0xc1, 0x4f, 0x80, 0x24, 0x83, 0x2b |
| 11 |
}; |
| 12 |
|
| 13 |
/* Preconditions: a is square or zero */ |
| 14 |
|
| 15 |
void fe_sqrt(fe out, const fe a) |
| 16 |
{ |
| 17 |
fe exp, b, b2, bi, i; |
| 18 |
#ifndef NDEBUG |
| 19 |
fe legendre, zero, one; |
| 20 |
#endif |
| 21 |
|
| 22 |
fe_frombytes(i, i_bytes); |
| 23 |
fe_pow22523(exp, a); /* b = a^(q-5)/8 */ |
| 24 |
|
| 25 |
/* PRECONDITION: legendre symbol == 1 (square) or 0 (a == zero) */ |
| 26 |
#ifndef NDEBUG |
| 27 |
fe_sq(legendre, exp); /* in^((q-5)/4) */ |
| 28 |
fe_sq(legendre, legendre); /* in^((q-5)/2) */ |
| 29 |
fe_mul(legendre, legendre, a); /* in^((q-3)/2) */ |
| 30 |
fe_mul(legendre, legendre, a); /* in^((q-1)/2) */ |
| 31 |
|
| 32 |
fe_0(zero); |
| 33 |
fe_1(one); |
| 34 |
assert(fe_isequal(legendre, zero) || fe_isequal(legendre, one)); |
| 35 |
#endif |
| 36 |
|
| 37 |
fe_mul(b, a, exp); /* b = a * a^(q-5)/8 */ |
| 38 |
fe_sq(b2, b); /* b^2 = a * a^(q-1)/4 */ |
| 39 |
|
| 40 |
/* note b^4 == a^2, so b^2 == a or -a |
| 41 |
* if b^2 != a, multiply it by sqrt(-1) */ |
| 42 |
fe_mul(bi, b, i); |
| 43 |
fe_cmov(b, bi, 1 ^ fe_isequal(b2, a)); |
| 44 |
fe_copy(out, b); |
| 45 |
|
| 46 |
/* PRECONDITION: out^2 == a */ |
| 47 |
#ifndef NDEBUG |
| 48 |
fe_sq(b2, out); |
| 49 |
assert(fe_isequal(a, b2)); |
| 50 |
#endif |
| 51 |
} |