base.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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(32):
  46. print "{"
  47. Bij = Bi
  48. for j in range(8):
  49. print " {"
  50. print " {",radix255(Bij[1]+Bij[0]),"},"
  51. print " {",radix255(Bij[1]-Bij[0]),"},"
  52. print " {",radix255(2*d*Bij[0]*Bij[1]),"},"
  53. Bij = edwards(Bij,Bi)
  54. print " },"
  55. print "},"
  56. for k in range(8):
  57. Bi = edwards(Bi,Bi)