curve.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import random
  2. from point import Point
  3. '''
  4. 'secp256k1',
  5. p=0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,
  6. a=0,
  7. b=7,
  8. g=(0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8),
  9. # Subgroup order.
  10. n=0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141,
  11. # Subgroup cofactor.
  12. h=1,
  13. '''
  14. # y2 = x3 + ax + b
  15. class Curve:
  16. def __init__(self, p, a, b, gx, gy, n, h):
  17. # размер конечного поля
  18. self.p = p
  19. # коэффиценты уравнения a и b
  20. self.a = a
  21. self.b = b
  22. # базовая точка
  23. self.g = Point(
  24. curve = self,
  25. x = gx,
  26. y = gy
  27. )
  28. # порядок подруппы
  29. self.n = n
  30. # кофактор подгруппы
  31. self.h = h
  32. def point(self, x, y):
  33. return Point(
  34. curve = self,
  35. x = x,
  36. y = y
  37. )
  38. # Обратное деление по модулю p кривой
  39. def inverseMod(self, k, point):
  40. if k == 0:
  41. raise ZeroDivisionError('division by zero')
  42. if k < 0:
  43. # k ** -1 = p - (-k) ** -1 (mod p)
  44. return point - self.inverseMod(-k, point)
  45. # Расширенный алгоритм Евклида
  46. s, old_s = 0, 1
  47. t, old_t = 1, 0
  48. r, old_r = point, k
  49. while r != 0:
  50. quotient = old_r // r
  51. old_r, r = r, old_r - quotient * r
  52. old_s, s = s, old_s - quotient * s
  53. old_t, t = t, old_t - quotient * t
  54. gcd, x, y = old_r, old_s, old_t
  55. #assert gcd == 1
  56. #assert (k * x) % p == 1
  57. return x % point
  58. def randomKeypair(self):
  59. keyPriv = random.randrange(1, self.n)
  60. keyPub = self.g * keyPriv
  61. return keyPriv, keyPub
  62. def keyPub(self, keyPriv):
  63. return self.g * keyPriv
  64. #################################
  65. c = Curve(
  66. p = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f,
  67. a = 0,
  68. b = 7,
  69. gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798,
  70. gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8,
  71. n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141,
  72. h = 1
  73. )
  74. # 0x774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb,
  75. # 0xd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b
  76. #pub = c.keyPub(11)
  77. #print(pub.show())
  78. #exit(0)
  79. aPriv, aPub = c.randomKeypair()
  80. bPriv, bPub = c.randomKeypair()
  81. print(hex(aPriv))
  82. print(aPub.show())
  83. #aS = scalar_mult(alice_private_key, bob_public_key)
  84. aS = bPub * aPriv
  85. bS = aPub * bPriv
  86. print(aS.show())
  87. print(bS.show())