reduce_mask_51, MASK64, MASK128)
from copy import deepcopy
-def curve25519_mul(r, s):
- t = [0] * 5 # all 128-bit
- r = deepcopy(r)
- s = deepcopy(s)
+def curve25519_mul_1st(t, r, s, dbg=True):
for i in range(5):
- print("t%d += " % i, end='')
+ if dbg: print("t%d += " % i, end='')
for j in range(i+1):
sidx = i-j
- print("r%d*s%d + " % (j, sidx), end='')
+ if dbg: print("r%d*s%d + " % (j, sidx), end='')
t[i] += (r[j] * s[sidx]) & MASK128
- print()
+ if dbg: print()
+
+
+def curve25519_mul_2nd(r):
for i in range(1,5):
r[i] *= 19
- print()
+def curve25519_mul_3rd(t, r, s, dbg=True):
+
+ if dbg: print()
for i in range(4,0,-1):
tidx = 4-i
- print("t%d += " % tidx, end='')
+ if dbg: print("t%d += " % tidx, end='')
for j in range(i):
jidx, sidx = 4-j, 5-(i-j)
- print("r%d*s%d + " % (jidx, sidx), end='')
+ if dbg: print("r%d*s%d + " % (jidx, sidx), end='')
t[tidx] += (r[jidx] * s[sidx]) & MASK128
- print()
+ if dbg: print()
+
+def curve25519_mul_4th(t, r, dbg=True):
# this is the one where i *think* it possible to do some sort
# of single-operation similar to dsld.
c = 0
for i in range(5):
- print("carry %d" % i, hex(c), hex(t[i]), end='')
+ if dbg: print("carry %d" % i, hex(c), hex(t[i]), end='')
t[i] = add128_64(t[i], c)
r[i] = lo128(t[i]) & reduce_mask_51
c = shr128(t[i], 51)
- print()
+ if dbg: print()
+ return c
+
+def curve25519_mul_5th(r, c):
r[0] += c * 19; c = r[0] >> 51; r[0] = r[0] & reduce_mask_51;
r[1] += c;
return r
+def curve25519_mul(r, s, dbg=True):
+
+ t = [0] * 5 # all 128-bit
+ r = deepcopy(r)
+ s = deepcopy(s)
+
+ curve25519_mul_1st(t, r, s, dbg=dbg)
+ curve25519_mul_2nd(r)
+ curve25519_mul_3rd(t, r, s, dbg=dbg)
+ c = curve25519_mul_4th(t, r, dbg=dbg)
+ curve25519_mul_5th(r, c)
+
+ return r
+
def contract(a): # put array back to a bignum
res = 0