| 1 |
#include <string.h> |
| 2 |
#include "fe.h" |
| 3 |
#include "ge.h" |
| 4 |
#include "crypto_uint32.h" |
| 5 |
#include "crypto_hash_sha512.h" |
| 6 |
#include "crypto_additions.h" |
| 7 |
|
| 8 |
unsigned int legendre_is_nonsquare(fe in) |
| 9 |
{ |
| 10 |
fe temp; |
| 11 |
unsigned char bytes[32]; |
| 12 |
fe_pow22523(temp, in); /* temp = in^((q-5)/8) */ |
| 13 |
fe_sq(temp, temp); /* in^((q-5)/4) */ |
| 14 |
fe_sq(temp, temp); /* in^((q-5)/2) */ |
| 15 |
fe_mul(temp, temp, in); /* in^((q-3)/2) */ |
| 16 |
fe_mul(temp, temp, in); /* in^((q-1)/2) */ |
| 17 |
|
| 18 |
/* temp is now the Legendre symbol: |
| 19 |
* 1 = square |
| 20 |
* 0 = input is zero |
| 21 |
* -1 = nonsquare |
| 22 |
*/ |
| 23 |
fe_tobytes(bytes, temp); |
| 24 |
return 1 & bytes[31]; |
| 25 |
} |
| 26 |
|
| 27 |
void elligator(fe u, const fe r) |
| 28 |
{ |
| 29 |
/* r = input |
| 30 |
* x = -A/(1+2r^2) # 2 is nonsquare |
| 31 |
* e = (x^3 + Ax^2 + x)^((q-1)/2) # legendre symbol |
| 32 |
* if e == 1 (square) or e == 0 (because x == 0 and 2r^2 + 1 == 0) |
| 33 |
* u = x |
| 34 |
* if e == -1 (nonsquare) |
| 35 |
* u = -x - A |
| 36 |
*/ |
| 37 |
fe A, one, twor2, twor2plus1, twor2plus1inv; |
| 38 |
fe x, e, Atemp, uneg; |
| 39 |
unsigned int nonsquare; |
| 40 |
|
| 41 |
fe_1(one); |
| 42 |
fe_0(A); |
| 43 |
A[0] = 486662; /* A = 486662 */ |
| 44 |
|
| 45 |
fe_sq2(twor2, r); /* 2r^2 */ |
| 46 |
fe_add(twor2plus1, twor2, one); /* 1+2r^2 */ |
| 47 |
fe_invert(twor2plus1inv, twor2plus1); /* 1/(1+2r^2) */ |
| 48 |
fe_mul(x, twor2plus1inv, A); /* A/(1+2r^2) */ |
| 49 |
fe_neg(x, x); /* x = -A/(1+2r^2) */ |
| 50 |
|
| 51 |
fe_mont_rhs(e, x); /* e = x^3 + Ax^2 + x */ |
| 52 |
nonsquare = legendre_is_nonsquare(e); |
| 53 |
|
| 54 |
fe_0(Atemp); |
| 55 |
fe_cmov(Atemp, A, nonsquare); /* 0, or A if nonsquare */ |
| 56 |
fe_add(u, x, Atemp); /* x, or x+A if nonsquare */ |
| 57 |
fe_neg(uneg, u); /* -x, or -x-A if nonsquare */ |
| 58 |
fe_cmov(u, uneg, nonsquare); /* x, or -x-A if nonsquare */ |
| 59 |
} |
| 60 |
|
| 61 |
void hash_to_point(ge_p3* p, const unsigned char* in, const unsigned long in_len) |
| 62 |
{ |
| 63 |
unsigned char hash[64]; |
| 64 |
fe h, u; |
| 65 |
unsigned char sign_bit; |
| 66 |
ge_p3 p3; |
| 67 |
|
| 68 |
crypto_hash_sha512(hash, in, in_len); |
| 69 |
|
| 70 |
/* take the high bit as Edwards sign bit */ |
| 71 |
sign_bit = (hash[31] & 0x80) >> 7; |
| 72 |
hash[31] &= 0x7F; |
| 73 |
fe_frombytes(h, hash); |
| 74 |
elligator(u, h); |
| 75 |
|
| 76 |
ge_montx_to_p3(&p3, u, sign_bit); |
| 77 |
ge_scalarmult_cofactor(p, &p3); |
| 78 |
} |
| 79 |
|
| 80 |
|