base2.py 1.2 KB

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