Debian Codegraph @

crypto_mGnP/ed25519/ref10/point26.py

raw
1 #!/usr/bin/env python3
2
3 q = 2**255 - 19
4 l = 2**252 + 27742317777372353535851937790883648493
5
6 def expmod(b,e,m):
7 if e == 0: return 1
8 t = expmod(b,e//2,m)**2 % m
9 if e & 1: t = (t*b) % m
10 return t
11
12 def inv(x):
13 return expmod(x,q-2,q)
14
15 d = -121665 * inv(121666)
16 I = expmod(2,(q-1)//4,q)
17
18 def xrecover(y):
19 xx = (y*y-1) * inv(d*y*y+1)
20 x = expmod(xx,(q+3)//8,q)
21 if (x*x - xx) % q != 0: x = (x*I) % q
22 if x % 2 != 0: x = q-x
23 return x
24
25 def isoncurve(P):
26 x,y = P
27 return (-x*x+y*y-1-d*x**2*y**2) % q == 0
28
29 By = 4 * inv(5)
30 Bx = xrecover(By)
31 B = Bx%q,By%q
32
33 assert isoncurve(B)
34
35 def edwards(P,Q):
36 x1,y1 = P
37 x2,y2 = Q
38 x3 = (x1*y2+x2*y1) * inv(1+d*x1*x2*y1*y2)
39 y3 = (y1*y2+x1*x2) * inv(1-d*x1*x2*y1*y2)
40 return x3%q,y3%q
41
42 def scalarmult(P,e):
43 assert e >= 0
44 if e == 0: return 0,1
45 Q = scalarmult(P,e//2)
46 Q = edwards(Q,Q)
47 if e & 1: Q = edwards(P,Q)
48 return Q
49
50 assert scalarmult(B,l) == (0,1)
51
52 Cy = 26 # minimum integer >1 giving C on curve and order l
53 Cx = xrecover(Cy)
54 C = Cx%q,Cy%q
55 assert isoncurve(C)
56 assert scalarmult(C,l) == (0,1)
57
58 # sanity checks:
59 # C is not a small multiple of B
60 # namely (0,1) or (+-...,4/5) or (+-...,-985469/985549) or ...
61 # and B is not a small multiple of C
62 # namely (0,1) or (+-...,10) or (+-...,-596219233/596219333) or ...
63 # and similarly for other small relations: e.g., 2B = 3C
64 # could do more serious discrete-log check
65
66 def hassmallrelation(A,B):
67 jAyset = set()
68 jA = 0,1
69 for j in range(1,1000):
70 jA = edwards(jA,A)
71 jAyset.add(jA[1])
72 jB = 0,1
73 for j in range(1,1000):
74 jB = edwards(jB,B)
75 if jB[1] in jAyset: return True
76 return False
77
78 testy = 333922976373947162567639162515495974004 * inv(333933611346170188668120256727948534525)
79 testx = xrecover(testy)
80 test = testx%q,testy%q
81 assert hassmallrelation(test,B)
82 assert not hassmallrelation(C,B)
83
84 def radix255(x):
85 x = x % q
86 if x + x > q: x -= q
87 x = [x,0,0,0,0,0,0,0,0,0]
88 bits = [26,25,26,25,26,25,26,25,26,25]
89 for i in range(9):
90 carry = (x[i] + 2**(bits[i]-1)) // 2**bits[i]
91 x[i] -= carry * 2**bits[i]
92 x[i + 1] += carry
93 result = ""
94 for i in range(9):
95 result = result+str(x[i])+","
96 result = result+str(x[9])
97 return result
98
99 print('static const fe point26_x = {')
100 print('//',C[0])
101 print(radix255(C[0]))
102 print('} ;')
103 print('static const fe point26_y = {')
104 print('//',C[1])
105 print(radix255(C[1]))
106 print('} ;')