Skip to content

Instantly share code, notes, and snippets.

@afiodorov
Created July 14, 2019 11:21
Show Gist options
  • Save afiodorov/c3ae3a3aaeb8505fc3941d003b90474b to your computer and use it in GitHub Desktop.
Save afiodorov/c3ae3a3aaeb8505fc3941d003b90474b to your computer and use it in GitHub Desktop.
toy ECDSA
# EC, Field are in http://afiodorov.github.io/2019/06/18/elliptic/
from dataclasses import dataclass
from random import randint
@dataclass
class Signature:
sig: int
pp: EC.Point
randomx: int
def __post_init__(self):
self.sig = Field(o).n(self.sig)
self.randomx = Field(o).n(self.randomx)
def sign(gen_point, secret, msg) -> Signature:
k = randint(1, o)
R = k * gen_point
pp = gen_point * secret
sig = (Field(o).n(msg) + R.x.a * secret) / k
return Signature(sig.a, pp, R.x.a)
def verify(gen_point, msg, sig: Signature) -> bool:
u = msg / sig.sig
v = sig.randomx / sig.sig
return (u.a * gen_point + v.a * sig.pp).x.a == sig.randomx.a
p = 2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 - 1
x = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
y = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
o = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
point = EC(0, 7).point(Field(p).n(x), y)
assert (o * point).zero
assert (o - 1) * point == -point # this implies above
def S256Point(x, y):
p = 2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 - 1
return EC(0, 7).point(Field(p).n(x), y)
pp = S256Point(0x04519fac3d910ca7e7138f7013706f619fa8f033e6ec6e09370ea38cee6a7574,
0x82b51eab8c27c66e26c858a079bcdf4f1ada34cec420cafc7eac1a42216fb6c4)
s = 0x8ca63759c1157ebeaec0d03cecca119fc9a75bf8e6d0fa65c841c8e2738cdaec
randomx = 0x37206a0610995c58074999cb9767b87af4c4978db68c06e8e6e81d282047a7c6
sig = Signature(s, pp, randomx)
msg = 0xbc62d4b80d9e36da29c16c5d4d9f11731f36052c72401a76c23c0fb5a9b74423
verify(point, msg, sig)
verify(point, 10, sign(point, 102301, 10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment