-
Notifications
You must be signed in to change notification settings - Fork 92
/
ecc.py
729 lines (644 loc) · 25.4 KB
/
ecc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
from io import BytesIO
from random import randint
from unittest import TestCase
import hmac
import hashlib
from helper import encode_base58_checksum, hash160
class FieldElement:
def __init__(self, num, prime):
if num >= prime or num < 0:
error = f"Num {num} not in field range 0 to {prime-1}"
raise ValueError(error)
self.num = num
self.prime = prime
def __eq__(self, other):
if other is None:
return False
return self.num == other.num and self.prime == other.prime
def __ne__(self, other):
# this should be the inverse of the == operator
return not (self == other)
def __repr__(self):
return f"FieldElement_{self.prime}({self.num})"
def __add__(self, other):
if self.prime != other.prime:
raise TypeError("Cannot add two numbers in different Fields")
# self.num and other.num are the actual values
num = (self.num + other.num) % self.prime
# self.prime is what you'll need to mod against
prime = self.prime
# You need to return an element of the same class
# use: self.__class__(num, prime)
return self.__class__(num, prime)
def __sub__(self, other):
if self.prime != other.prime:
raise TypeError("Cannot add two numbers in different Fields")
# self.num and other.num are the actual values
num = (self.num - other.num) % self.prime
# self.prime is what you'll need to mod against
prime = self.prime
# You need to return an element of the same class
# use: self.__class__(num, prime)
return self.__class__(num, prime)
def __mul__(self, other):
if self.prime != other.prime:
raise TypeError("Cannot add two numbers in different Fields")
# self.num and other.num are the actual values
num = (self.num * other.num) % self.prime
# self.prime is what you'll need to mod against
prime = self.prime
# You need to return an element of the same class
# use: self.__class__(num, prime)
return self.__class__(num, prime)
def __pow__(self, n):
# self.num is the base, n is the exponent
# self.prime is what you'll need to mod against
prime = self.prime
# use pow(base, exponent, prime) to calculate the number
num = pow(self.num, n, prime)
# use: self.__class__(num, prime)
return self.__class__(num, prime)
def __truediv__(self, other):
if self.prime != other.prime:
raise TypeError("Cannot add two numbers in different Fields")
# self.num and other.num are the acvtual values
num = (self.num * pow(other.num, self.prime - 2, self.prime)) % self.prime
# self.prime is what you'll need to mod against
prime = self.prime
# use fermat's little theorem:
# self.num**(p-1) % p == 1
# this means:
# 1/n == pow(n, p-2, p)
# You need to return an element of the same class
# use: self.__class__(num, prime)
return self.__class__(num, prime)
def __rmul__(self, coefficient):
num = (self.num * coefficient) % self.prime
return self.__class__(num=num, prime=self.prime)
class FieldElementTest(TestCase):
def test_ne(self):
a = FieldElement(2, 31)
b = FieldElement(2, 31)
c = FieldElement(15, 31)
self.assertEqual(a, b)
self.assertTrue(a != c)
self.assertFalse(a != b)
def test_add(self):
a = FieldElement(2, 31)
b = FieldElement(15, 31)
self.assertEqual(a + b, FieldElement(17, 31))
a = FieldElement(17, 31)
b = FieldElement(21, 31)
self.assertEqual(a + b, FieldElement(7, 31))
def test_sub(self):
a = FieldElement(29, 31)
b = FieldElement(4, 31)
self.assertEqual(a - b, FieldElement(25, 31))
a = FieldElement(15, 31)
b = FieldElement(30, 31)
self.assertEqual(a - b, FieldElement(16, 31))
def test_mul(self):
a = FieldElement(24, 31)
b = FieldElement(19, 31)
self.assertEqual(a * b, FieldElement(22, 31))
def test_pow(self):
a = FieldElement(17, 31)
self.assertEqual(a**3, FieldElement(15, 31))
a = FieldElement(5, 31)
b = FieldElement(18, 31)
self.assertEqual(a**5 * b, FieldElement(16, 31))
def test_div(self):
a = FieldElement(3, 31)
b = FieldElement(24, 31)
self.assertEqual(a / b, FieldElement(4, 31))
a = FieldElement(17, 31)
self.assertEqual(a**-3, FieldElement(29, 31))
a = FieldElement(4, 31)
b = FieldElement(11, 31)
self.assertEqual(a**-4 * b, FieldElement(13, 31))
class Point:
def __init__(self, x, y, a, b):
self.a = a
self.b = b
self.x = x
self.y = y
# x being None and y being None represents the point at infinity
# Check for that here since the equation below won't make sense
# with None values for both.
if self.x is None and self.y is None:
return
# make sure that the elliptic curve equation is satisfied
# y**2 == x**3 + a*x + b
if self.y**2 != self.x**3 + a * x + b:
# if not, raise a ValueError
raise ValueError(f"({self.x}, {self.y}) is not on the curve")
def __eq__(self, other):
return (
self.x == other.x
and self.y == other.y
and self.a == other.a
and self.b == other.b
)
def __ne__(self, other):
# this should be the inverse of the == operator
return not (self == other)
def __repr__(self):
if self.x is None:
return "Point(infinity)"
else:
return f"Point({self.x.num},{self.y.num})_{self.x.prime}"
def __add__(self, other):
if self.a != other.a or self.b != other.b:
raise TypeError(f"Points {self}, {other} are not on the same curve")
# Case 0.0: self is the point at infinity, return other
if self.x is None:
return other
# Case 0.1: other is the point at infinity, return self
if other.x is None:
return self
# Case 1: self.x == other.x, self.y != other.y
# Result is point at infinity
if self.x == other.x and self.y != other.y:
# Remember to return an instance of this class:
# self.__class__(x, y, a, b)
return self.__class__(None, None, self.a, self.b)
# Case 2: self.x != other.x
if self.x != other.x:
# Formula (x3,y3)==(x1,y1)+(x2,y2)
# s=(y2-y1)/(x2-x1)
s = (other.y - self.y) / (other.x - self.x)
# x3=s**2-x1-x2
x = s**2 - self.x - other.x
# y3=s*(x1-x3)-y1
y = s * (self.x - x) - self.y
# use: self.__class__(x, y, self.a, self.b)
return self.__class__(x, y, self.a, self.b)
# Case 3: self == other
else:
# Formula (x3,y3)=(x1,y1)+(x1,y1)
# s=(3*x1**2+a)/(2*y1)
s = (3 * self.x**2 + self.a) / (2 * self.y)
# x3=s**2-2*x1
x = s**2 - 2 * self.x
# y3=s*(x1-x3)-y1
y = s * (self.x - x) - self.y
# use: self.__class__(x, y, self.a, self.b)
return self.__class__(x, y, self.a, self.b)
def __rmul__(self, coefficient):
# rmul calculates coefficient * self
coef = coefficient
current = self
# start at 0
result = self.__class__(None, None, self.a, self.b)
while coef:
# if the bit at this binary expansion is 1, add
if coef & 1:
result += current
# double the point
current += current
coef >>= 1
return result
class PointTest(TestCase):
def test_ne(self):
a = Point(x=3, y=-7, a=5, b=7)
b = Point(x=18, y=77, a=5, b=7)
self.assertTrue(a != b)
self.assertFalse(a != a)
def test_on_curve(self):
with self.assertRaises(ValueError):
Point(x=-2, y=4, a=5, b=7)
# these should not raise an error
Point(x=3, y=-7, a=5, b=7)
Point(x=18, y=77, a=5, b=7)
def test_add0(self):
a = Point(x=None, y=None, a=5, b=7)
b = Point(x=2, y=5, a=5, b=7)
c = Point(x=2, y=-5, a=5, b=7)
self.assertEqual(a + b, b)
self.assertEqual(b + a, b)
self.assertEqual(b + c, a)
def test_add1(self):
a = Point(x=3, y=7, a=5, b=7)
b = Point(x=-1, y=-1, a=5, b=7)
self.assertEqual(a + b, Point(x=2, y=-5, a=5, b=7))
def test_add2(self):
a = Point(x=-1, y=1, a=5, b=7)
self.assertEqual(a + a, Point(x=18, y=-77, a=5, b=7))
class ECCTest(TestCase):
def test_on_curve(self):
# tests the following points whether they are on the curve or not
# on curve y^2=x^3-7 over F_223:
# (192,105) (17,56) (200,119) (1,193) (42,99)
# the ones that aren't should raise a ValueError
prime = 223
a = FieldElement(0, prime)
b = FieldElement(7, prime)
valid_points = ((192, 105), (17, 56), (1, 193))
invalid_points = ((200, 119), (42, 99))
# iterate over valid points
for x_raw, y_raw in valid_points:
# Initialize points this way:
# x = FieldElement(x_raw, prime)
# y = FieldElement(y_raw, prime)
# Point(x, y, a, b)
x = FieldElement(x_raw, prime)
y = FieldElement(y_raw, prime)
# Creating the point should not result in an error
Point(x, y, a, b)
# iterate over invalid points
for x_raw, y_raw in invalid_points:
# Initialize points this way:
# x = FieldElement(x_raw, prime)
# y = FieldElement(y_raw, prime)
# Point(x, y, a, b)
x = FieldElement(x_raw, prime)
y = FieldElement(y_raw, prime)
# check that creating the point results in a ValueError
# use: with self.assertRaises(ValueError):
with self.assertRaises(ValueError):
Point(x, y, a, b)
def test_add(self):
# tests the following additions on curve y^2=x^3-7 over F_223:
# (192,105) + (17,56)
# (47,71) + (117,141)
# (143,98) + (76,66)
prime = 223
a = FieldElement(0, prime)
b = FieldElement(7, prime)
additions = (
# (x1, y1, x2, y2, x3, y3)
(192, 105, 17, 56, 170, 142),
(47, 71, 117, 141, 60, 139),
(143, 98, 76, 66, 47, 71),
)
# iterate over the additions
for x1_raw, y1_raw, x2_raw, y2_raw, x3_raw, y3_raw in additions:
# Initialize points this way:
# x1 = FieldElement(x1_raw, prime)
# y1 = FieldElement(y1_raw, prime)
# p1 = Point(x1, y1, a, b)
# x2 = FieldElement(x2_raw, prime)
# y2 = FieldElement(y2_raw, prime)
# p2 = Point(x2, y2, a, b)
# x3 = FieldElement(x3_raw, prime)
# y3 = FieldElement(y3_raw, prime)
# p3 = Point(x3, y3, a, b)
x1 = FieldElement(x1_raw, prime)
y1 = FieldElement(y1_raw, prime)
p1 = Point(x1, y1, a, b)
x2 = FieldElement(x2_raw, prime)
y2 = FieldElement(y2_raw, prime)
p2 = Point(x2, y2, a, b)
x3 = FieldElement(x3_raw, prime)
y3 = FieldElement(y3_raw, prime)
p3 = Point(x3, y3, a, b)
# check that p1 + p2 == p3
self.assertEqual(p1 + p2, p3)
def test_rmul(self):
# tests the following scalar multiplications
# 2*(192,105)
# 2*(143,98)
# 2*(47,71)
# 4*(47,71)
# 8*(47,71)
# 21*(47,71)
prime = 223
a = FieldElement(0, prime)
b = FieldElement(7, prime)
multiplications = (
# (coefficient, x1, y1, x2, y2)
(2, 192, 105, 49, 71),
(2, 143, 98, 64, 168),
(2, 47, 71, 36, 111),
(4, 47, 71, 194, 51),
(8, 47, 71, 116, 55),
(21, 47, 71, None, None),
)
# iterate over the multiplications
for s, x1_raw, y1_raw, x2_raw, y2_raw in multiplications:
# Initialize points this way:
# x1 = FieldElement(x1_raw, prime)
# y1 = FieldElement(y1_raw, prime)
# p1 = Point(x1, y1, a, b)
x1 = FieldElement(x1_raw, prime)
y1 = FieldElement(y1_raw, prime)
p1 = Point(x1, y1, a, b)
# initialize the second point based on whether it's the point at infinity
# x2 = FieldElement(x2_raw, prime)
# y2 = FieldElement(y2_raw, prime)
# p2 = Point(x2, y2, a, b)
if x2_raw is None:
p2 = Point(None, None, a, b)
else:
x2 = FieldElement(x2_raw, prime)
y2 = FieldElement(y2_raw, prime)
p2 = Point(x2, y2, a, b)
# check that the product is equal to the expected point
self.assertEqual(s * p1, p2)
A = 0
B = 7
P = 2**256 - 2**32 - 977
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
class S256Field(FieldElement):
def __init__(self, num, prime=None):
super().__init__(num=num, prime=P)
def hex(self):
return f"{self.num:x}".zfill(64)
def __repr__(self):
return self.hex()
def sqrt(self):
return self ** ((P + 1) // 4)
class S256Point(Point):
def __init__(self, x, y, a=None, b=None):
a, b = S256Field(A), S256Field(B)
if type(x) == int:
super().__init__(x=S256Field(x), y=S256Field(y), a=a, b=b)
else:
super().__init__(x=x, y=y, a=a, b=b)
def __repr__(self):
if self.x is None:
return "S256Point(infinity)"
else:
return f"S256Point({self.x.num:x},{self.y.num:x})"
def __rmul__(self, coefficient):
# we want to mod by N to make this simple
coef = coefficient % N
return super().__rmul__(coef)
def sec(self, compressed=True):
# returns the binary version of the sec format, NOT hex
# if compressed, starts with b'\x02' if self.y.num is even, b'\x03' if self.y is odd
# then self.x.num
# remember, you have to convert self.x.num/self.y.num to binary (some_integer.to_bytes(32, 'big'))
if compressed:
if self.y.num % 2 == 0:
return b"\x02" + self.x.num.to_bytes(32, "big")
else:
return b"\x03" + self.x.num.to_bytes(32, "big")
else:
# if non-compressed, starts with b'\x04' followod by self.x and then self.y
return (
b"\x04"
+ self.x.num.to_bytes(32, "big")
+ self.y.num.to_bytes(32, "big")
)
def address(self, compressed=True, network="mainnet"):
"""Returns the address string"""
# get the sec
sec = self.sec(compressed)
# hash160 the sec
h160 = hash160(sec)
# prefix is b'\x00' for mainnet, b'\x6f' for testnet/signet
if network in ("testnet", "signet"):
prefix = b"\x6f"
else:
prefix = b"\x00"
# return the encode_base58_checksum of the prefix and h160
return encode_base58_checksum(prefix + h160)
def verify(self, z, sig):
# remember sig.r and sig.s are the main things we're checking
# remember 1/s = pow(s, -1, N)
s_inv = pow(sig.s, -1, N)
# u = z / s
u = z * s_inv % N
# v = r / s
v = sig.r * s_inv % N
# u*G + v*P should have as the x coordinate, r
total = u * G + v * self
return total.x.num == sig.r
@classmethod
def parse(self, sec_bin):
"""returns a Point object from a compressed sec binary (not hex)"""
if sec_bin[0] == 4:
x = int(sec_bin[1:33].hex(), 16)
y = int(sec_bin[33:65].hex(), 16)
return S256Point(x=x, y=y)
is_even = sec_bin[0] == 2
x = S256Field(int(sec_bin[1:].hex(), 16))
# right side of the equation y^2 = x^3 + 7
alpha = x**3 + S256Field(B)
# solve for left side
beta = alpha.sqrt()
if beta.num % 2 == 0:
even_beta = beta
odd_beta = S256Field(P - beta.num)
else:
even_beta = S256Field(P - beta.num)
odd_beta = beta
if is_even:
return S256Point(x, even_beta)
else:
return S256Point(x, odd_beta)
G = S256Point(
0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8,
)
class S256Test(TestCase):
def test_order(self):
point = N * G
self.assertIsNone(point.x)
def test_pubpoint(self):
# write a test that tests the public point for the following
points = (
# secret, x, y
(
7,
0x5CBDF0646E5DB4EAA398F365F2EA7A0E3D419B7E0330E39CE92BDDEDCAC4F9BC,
0x6AEBCA40BA255960A3178D6D861A54DBA813D0B813FDE7B5A5082628087264DA,
),
(
1485,
0xC982196A7466FBBBB0E27A940B6AF926C1A74D5AD07128C82824A11B5398AFDA,
0x7A91F9EAE64438AFB9CE6448A1C133DB2D8FB9254E4546B6F001637D50901F55,
),
(
2**128,
0x8F68B9D2F63B5F339239C1AD981F162EE88C5678723EA3351B7B444C9EC4C0DA,
0x662A9F2DBA063986DE1D90C2B6BE215DBBEA2CFE95510BFDF23CBF79501FFF82,
),
(
2**240 + 2**31,
0x9577FF57C8234558F293DF502CA4F09CBC65A6572C842B39B366F21717945116,
0x10B49C67FA9365AD7B90DAB070BE339A1DAF9052373EC30FFAE4F72D5E66D053,
),
)
# iterate over points
for secret, x, y in points:
# initialize the secp256k1 point (S256Point)
point = S256Point(x, y)
# check that the secret*G is the same as the point
self.assertEqual(secret * G, point)
def test_sec(self):
coefficient = 999**3
uncompressed = "049d5ca49670cbe4c3bfa84c96a8c87df086c6ea6a24ba6b809c9de234496808d56fa15cc7f3d38cda98dee2419f415b7513dde1301f8643cd9245aea7f3f911f9"
compressed = (
"039d5ca49670cbe4c3bfa84c96a8c87df086c6ea6a24ba6b809c9de234496808d5"
)
point = coefficient * G
self.assertEqual(point.sec(compressed=False), bytes.fromhex(uncompressed))
self.assertEqual(point.sec(compressed=True), bytes.fromhex(compressed))
coefficient = 123
uncompressed = "04a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b"
compressed = (
"03a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5"
)
point = coefficient * G
self.assertEqual(point.sec(compressed=False), bytes.fromhex(uncompressed))
self.assertEqual(point.sec(compressed=True), bytes.fromhex(compressed))
coefficient = 42424242
uncompressed = "04aee2e7d843f7430097859e2bc603abcc3274ff8169c1a469fee0f20614066f8e21ec53f40efac47ac1c5211b2123527e0e9b57ede790c4da1e72c91fb7da54a3"
compressed = (
"03aee2e7d843f7430097859e2bc603abcc3274ff8169c1a469fee0f20614066f8e"
)
point = coefficient * G
self.assertEqual(point.sec(compressed=False), bytes.fromhex(uncompressed))
self.assertEqual(point.sec(compressed=True), bytes.fromhex(compressed))
def test_address(self):
secret = 888**3
mainnet_address = "148dY81A9BmdpMhvYEVznrM45kWN32vSCN"
signet_address = "mieaqB68xDCtbUBYFoUNcmZNwk74xcBfTP"
point = secret * G
self.assertEqual(
point.address(compressed=True, network="mainnet"), mainnet_address
)
self.assertEqual(
point.address(compressed=True, network="signet"), signet_address
)
secret = 321
mainnet_address = "1S6g2xBJSED7Qr9CYZib5f4PYVhHZiVfj"
signet_address = "mfx3y63A7TfTtXKkv7Y6QzsPFY6QCBCXiP"
point = secret * G
self.assertEqual(
point.address(compressed=False, network="mainnet"), mainnet_address
)
self.assertEqual(
point.address(compressed=False, network="signet"), signet_address
)
secret = 4242424242
mainnet_address = "1226JSptcStqn4Yq9aAmNXdwdc2ixuH9nb"
signet_address = "mgY3bVusRUL6ZB2Ss999CSrGVbdRwVpM8s"
point = secret * G
self.assertEqual(
point.address(compressed=False, network="mainnet"), mainnet_address
)
self.assertEqual(
point.address(compressed=False, network="signet"), signet_address
)
def test_verify(self):
point = S256Point(
0x887387E452B8EACC4ACFDE10D9AAF7F6D9A0F975AABB10D006E4DA568744D06C,
0x61DE6D95231CD89026E286DF3B6AE4A894A3378E393E93A0F45B666329A0AE34,
)
z = 0xEC208BAA0FC1C19F708A9CA96FDEFF3AC3F230BB4A7BA4AEDE4942AD003C0F60
r = 0xAC8D1C87E51D0D441BE8B3DD5B05C8795B48875DFFE00B7FFCFAC23010D3A395
s = 0x68342CEFF8935EDEDD102DD876FFD6BA72D6A427A3EDB13D26EB0781CB423C4
self.assertTrue(point.verify(z, Signature(r, s)))
z = 0x7C076FF316692A3D7EB3C3BB0F8B1488CF72E1AFCD929E29307032997A838A3D
r = 0xEFF69EF2B1BD93A66ED5219ADD4FB51E11A840F404876325A1E8FFE0529A2C
s = 0xC7207FEE197D27C618AEA621406F6BF5EF6FCA38681D82B2F06FDDBDCE6FEAB6
self.assertTrue(point.verify(z, Signature(r, s)))
def test_parse(self):
sec = bytes.fromhex(
"0349fc4e631e3624a545de3f89f5d8684c7b8138bd94bdd531d2e213bf016b278a"
)
point = S256Point.parse(sec)
want = 0xA56C896489C71DFC65701CE25050F542F336893FB8CD15F4E8E5C124DBF58E47
self.assertEqual(point.y.num, want)
class Signature:
def __init__(self, r, s):
self.r = r
self.s = s
def __repr__(self):
return f"Signature({self.r:x},{self.s:x})"
def der(self):
# convert the r part to bytes
rbin = self.r.to_bytes(32, byteorder="big")
# if rbin has a high bit, add a 00
if rbin[0] >= 128:
rbin = b"\x00" + rbin
result = bytes([2, len(rbin)]) + rbin
sbin = self.s.to_bytes(32, byteorder="big")
# if sbin has a high bit, add a 00
if sbin[0] >= 128:
sbin = b"\x00" + sbin
result += bytes([2, len(sbin)]) + sbin
return bytes([0x30, len(result)]) + result
@classmethod
def parse(cls, signature_bin):
s = BytesIO(signature_bin)
compound = s.read(1)[0]
if compound != 0x30:
raise RuntimeError("Bad Signature")
length = s.read(1)[0]
if length + 2 != len(signature_bin):
raise RuntimeError("Bad Signature Length")
marker = s.read(1)[0]
if marker != 0x02:
raise RuntimeError("Bad Signature")
rlength = s.read(1)[0]
r = int(s.read(rlength).hex(), 16)
marker = s.read(1)[0]
if marker != 0x02:
raise RuntimeError("Bad Signature")
slength = s.read(1)[0]
s = int(s.read(slength).hex(), 16)
if len(signature_bin) != 6 + rlength + slength:
raise RuntimeError("Signature too long")
return cls(r, s)
class SignatureTest(TestCase):
def test_der(self):
testcases = (
(1, 2),
(randint(0, 2**256), randint(0, 2**255)),
(randint(0, 2**256), randint(0, 2**255)),
)
for r, s in testcases:
sig = Signature(r, s)
der = sig.der()
sig2 = Signature.parse(der)
self.assertEqual(sig2.r, r)
self.assertEqual(sig2.s, s)
class PrivateKey:
def __init__(self, secret):
self.secret = secret
self.point = secret * G
def hex(self):
return f"{secret:x}".zfill(64)
def sign(self, z):
# we need use deterministic k
k = self.deterministic_k(z)
# r is the x coordinate of the resulting point k*G
r = (k * G).x.num
# remember 1/k = pow(k, -1, N)
k_inv = pow(k, -1, N)
# s = (z+r*secret) / k
s = (z + r * self.secret) * k_inv % N
if s > N / 2:
s = N - s
# return an instance of Signature:
# Signature(r, s)
return Signature(r, s)
def deterministic_k(self, z):
k = b"\x00" * 32
v = b"\x01" * 32
if z > N:
z -= N
z_bytes = z.to_bytes(32, "big")
secret_bytes = self.secret.to_bytes(32, "big")
s256 = hashlib.sha256
k = hmac.new(k, v + b"\x00" + secret_bytes + z_bytes, s256).digest()
v = hmac.new(k, v, s256).digest()
k = hmac.new(k, v + b"\x01" + secret_bytes + z_bytes, s256).digest()
v = hmac.new(k, v, s256).digest()
while True:
v = hmac.new(k, v, s256).digest()
candidate = int.from_bytes(v, "big")
if candidate >= 1 and candidate < N:
return candidate
k = hmac.new(k, v + b"\x00", s256).digest()
v = hmac.new(k, v, s256).digest()
class PrivateKeyTest(TestCase):
def test_sign(self):
pk = PrivateKey(randint(0, 2**256))
z = randint(0, 2**256)
sig = pk.sign(z)
self.assertTrue(pk.point.verify(z, sig))