a = 0
b = 7
G = (0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798, 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8)
n = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141
E = EllipticCurve(GF(p), [a, b])
G = E(G)
from hashlib import sha256
import struct
def bytes_to_long(s):
"""bytes_to_long(strinng) : long
Convert a byte string to a long integer.
This is (essentially) the inverse of long_to_bytes().
"""
acc = 0L
unpack = struct.unpack
length = len(s)
if length % 4:
extra = (4 - length % 4)
s = b('\000') * extra + s
length = length + extra
for i in range(0, length, 4):
acc = (acc << 32) + unpack('>I', s[i:i+4])[0]
return acc
def H(m):
h = sha256()
h.update(m)
return bytes_to_long(h.digest())
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, x, y = egcd(b % a, a)
return (g, y - (b // a) * x, x)
def inverse(b, n):
g, x, _ = egcd(b, n)
if g == 1:
return x % n
def sign(m,k,d):
k = k
kG= k*G
rx,ry=kG.xy()
r = int(rx)
s = ((H(m) + d*r)*inverse(k, n)) % n
return r, s,H(m)
def calc_x(k_key,r,s,z):
x=(s*k_key - z)*inverse(r,n)%n
return x,n-x
def calc_k(private,r,s,z):
k=(r*private + z)*inverse(s,n)%n
return k,n-k
m1=b"bitcoin"
k_key=100
private=25
r,s,z = sign(m1,k_key,private)
print("1 rsz",r,s,z)
print("k_key=",calc_k(private,int(r),int(s),int(z)))
print("private=",calc_x(k_key,int(r),int(s),int(z)))
#new:
r2=105562457083132745572708143974180364633865373973280165462544121334166431725102
s2=103297023888398300822393645768628709580138523147555505327497101680694113007481
z2=48363072098642544965975966934959923879938723004602706934166367375051848994308
print("k_key=",calc_k(private,int(r2),int(s2),int(z2)))
print("private=",calc_x(k_key,int(r2),int(s2),int(z2)))
#test
print("r==r2",r==r2)
any explain what and why it is work? , and any attack?