| 1 |
b = 256 |
| 2 |
q = 2**255 - 19 |
| 3 |
l = 2**252 + 27742317777372353535851937790883648493 |
| 4 |
|
| 5 |
def expmod(b,e,m): |
| 6 |
if e == 0: return 1 |
| 7 |
t = expmod(b,e/2,m)**2 % m |
| 8 |
if e & 1: t = (t*b) % m |
| 9 |
return t |
| 10 |
|
| 11 |
def inv(x): |
| 12 |
return expmod(x,q-2,q) |
| 13 |
|
| 14 |
d = -121665 * inv(121666) |
| 15 |
I = expmod(2,(q-1)/4,q) |
| 16 |
|
| 17 |
def xrecover(y): |
| 18 |
xx = (y*y-1) * inv(d*y*y+1) |
| 19 |
x = expmod(xx,(q+3)/8,q) |
| 20 |
if (x*x - xx) % q != 0: x = (x*I) % q |
| 21 |
if x % 2 != 0: x = q-x |
| 22 |
return x |
| 23 |
|
| 24 |
By = 4 * inv(5) |
| 25 |
Bx = xrecover(By) |
| 26 |
B = [Bx % q,By % q] |
| 27 |
|
| 28 |
def edwards(P,Q): |
| 29 |
x1 = P[0] |
| 30 |
y1 = P[1] |
| 31 |
x2 = Q[0] |
| 32 |
y2 = Q[1] |
| 33 |
x3 = (x1*y2+x2*y1) * inv(1+d*x1*x2*y1*y2) |
| 34 |
y3 = (y1*y2+x1*x2) * inv(1-d*x1*x2*y1*y2) |
| 35 |
return [x3 % q,y3 % q] |
| 36 |
|
| 37 |
def radix255(x): |
| 38 |
x = x % q |
| 39 |
if x + x > q: x -= q |
| 40 |
x = [x,0,0,0,0,0,0,0,0,0] |
| 41 |
bits = [26,25,26,25,26,25,26,25,26,25] |
| 42 |
for i in range(9): |
| 43 |
carry = (x[i] + 2**(bits[i]-1)) / 2**bits[i] |
| 44 |
x[i] -= carry * 2**bits[i] |
| 45 |
x[i + 1] += carry |
| 46 |
result = "" |
| 47 |
for i in range(9): |
| 48 |
result = result+str(x[i])+"," |
| 49 |
result = result+str(x[9]) |
| 50 |
return result |
| 51 |
|
| 52 |
Bi = B |
| 53 |
|
| 54 |
for i in range(8): |
| 55 |
print " {" |
| 56 |
print " {",radix255(Bi[1]+Bi[0]),"}," |
| 57 |
print " {",radix255(Bi[1]-Bi[0]),"}," |
| 58 |
print " {",radix255(2*d*Bi[0]*Bi[1]),"}," |
| 59 |
print " }," |
| 60 |
Bi = edwards(B,edwards(B,Bi)) |