-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
68 lines (40 loc) · 1.37 KB
/
utils.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
import binascii
import hashlib
import random
import ecdsa
# This elliptic curve is used by bitcoin too
CURVE = ecdsa.SECP256k1
def sha1_int(key):
if hasattr(key, 'encode'):
key = key.encode()
digest = hashlib.sha1(key).digest()
return int.from_bytes(digest, byteorder='big', signed=False)
def random_id():
identifier = random.getrandbits(160)
return sha1_int(identifier.to_bytes(20, byteorder='big', signed=False))
def gen_pub_pvt():
"""
Generate key-pair.
"""
sk = ecdsa.SigningKey.generate(curve=CURVE)
vk = sk.get_verifying_key()
pvt_key = binascii.hexlify(sk.to_string()).decode()
pub_key = binascii.hexlify(vk.to_string()).decode()
return pub_key, pvt_key
def sign_msg(pvt_key, msg):
pvt_key = binascii.unhexlify(pvt_key.encode())
sk = ecdsa.SigningKey.from_string(pvt_key, curve=CURVE)
sign = sk.sign(msg.encode())
sign = binascii.hexlify(sign).decode()
return sign
def verify_msg(pub_key, msg, sign):
pub_key = binascii.unhexlify(pub_key.encode())
vk = ecdsa.VerifyingKey.from_string(pub_key, curve=CURVE)
sign = binascii.unhexlify(sign.encode())
return vk.verify(sign, msg.encode())
if __name__ == '__main__':
# Test out signing & verification
msg = "Shadab Zafar"
pub, pvt = gen_pub_pvt()
sign = sign_msg(pvt, msg)
assert verify_msg(pub, msg, sign)