/
r_exploit_schnorr.py
executable file
·76 lines (64 loc) · 2.4 KB
/
r_exploit_schnorr.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
#!/usr/bin/env python3
import hashlib
import binascii
import random
p = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
n = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
def inv(a, n):
if a == 0:
return 0
lm, hm = 1, 0
low, high = a % n, n
while low > 1:
r = high//low
nm, new = hm-lm*r, high-low*r
lm, low, hm, high = nm, new, lm, low
return lm % n
def point_add(p1, p2):
if (p1 is None):
return p2
if (p2 is None):
return p1
if (p1[0] == p2[0] and p1[1] != p2[1]):
return None
if (p1 == p2):
lam = (3 * p1[0] * p1[0] * pow(2 * p1[1], p - 2, p)) % p
else:
lam = ((p2[1] - p1[1]) * pow(p2[0] - p1[0], p - 2, p)) % p
x3 = (lam * lam - p1[0] - p2[0]) % p
return (x3, (lam * (p1[0] - x3) - p1[1]) % p)
def point_mul(p, n):
r = None
for i in range(256):
if ((n >> i) & 1):
r = point_add(r, p)
p = point_add(p, p)
return r
def bytes_point(p):
return (b'\x03' if p[1] & 1 else b'\x02') + p[0].to_bytes(32, byteorder="big")
def sha256(b):
return int.from_bytes(hashlib.sha256(b).digest(), byteorder="big")
def jacobi(x):
return pow(x, (p - 1) // 2, p)
def schnorr_sign(msg, seckey, k):
R = point_mul(G, k)
if jacobi(R[1]) != 1:
k = n - k
e = sha256(R[0].to_bytes(32, byteorder="big") + bytes_point(point_mul(G, seckey)) + msg.encode())
return (R[0], (k + e * seckey) % n)
# Generate secret key & the corresponding public key and address
secret_key = random.SystemRandom().randrange(1, n)
public_key = point_mul(G, secret_key)
# Sign 2 differents messages with same k
signing_k = random.SystemRandom().randrange(1, n)
sig1_r, sig1_s = schnorr_sign('first_message', secret_key, signing_k)
sig2_r, sig2_s = schnorr_sign('second_message', secret_key, signing_k)
assert sig1_r == sig2_r
print('+ R used = {:x}'.format(sig1_r))
# Calculate private key from signatures
e1 = sha256(sig1_r.to_bytes(32, byteorder="big") + bytes_point(public_key) + 'first_message'.encode())
e2 = sha256(sig2_r.to_bytes(32, byteorder="big") + bytes_point(public_key) + 'second_message'.encode())
d = ((sig1_s - sig2_s) * inv(e1 - e2, n)) % n
assert secret_key == d
print('+ Calc key = {0}'.format(d))