1
|
|
|
from ecdsa import SigningKey, SECP256k1 |
2
|
|
|
from ecdsa import util as ecdsaUtil |
3
|
|
|
import binascii |
4
|
|
|
import hashlib |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
def generate_pem(): |
8
|
|
|
sk = SigningKey.generate(curve=SECP256k1) |
9
|
|
|
pem = sk.to_pem() |
10
|
|
|
pem = pem.decode("utf-8") |
11
|
|
|
return pem |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
def get_sin_from_pem(pem): |
15
|
|
|
public_key = get_compressed_public_key_from_pem(pem) |
16
|
|
|
version = get_version_from_compressed_key(public_key) |
17
|
|
|
checksum = get_checksum_from_version(version) |
18
|
|
|
return base58encode(version + checksum) |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
def get_compressed_public_key_from_pem(pem): |
22
|
|
|
vks = SigningKey.from_pem(pem).get_verifying_key().to_string() |
23
|
|
|
bts = binascii.hexlify(vks) |
24
|
|
|
compressed = compress_key(bts) |
25
|
|
|
return compressed |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
def sign(message, pem): |
29
|
|
|
message = message.encode() |
30
|
|
|
sk = SigningKey.from_pem(pem) |
31
|
|
|
signed = sk.sign(message, hashfunc=hashlib.sha256, |
32
|
|
|
sigencode=ecdsaUtil.sigencode_der) |
33
|
|
|
return binascii.hexlify(signed).decode() |
34
|
|
|
|
35
|
|
|
|
36
|
|
|
def base58encode(hexastring): |
37
|
|
|
chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' |
38
|
|
|
int_val = int(hexastring, 16) |
39
|
|
|
encoded = encode58("", int_val, chars) |
40
|
|
|
return encoded |
41
|
|
|
|
42
|
|
|
|
43
|
|
|
def encode58(string, int_val, chars): |
44
|
|
|
if int_val == 0: |
45
|
|
|
return string |
46
|
|
|
else: |
47
|
|
|
new_val, rem = divmod(int_val, 58) |
48
|
|
|
new_string = (chars[rem]) + string |
49
|
|
|
return encode58(new_string, new_val, chars) |
50
|
|
|
|
51
|
|
|
|
52
|
|
|
def get_checksum_from_version(version): |
53
|
|
|
return sha_digest(sha_digest(version))[0:8] |
54
|
|
|
|
55
|
|
|
|
56
|
|
|
def get_version_from_compressed_key(key): |
57
|
|
|
sh2 = sha_digest(key) |
58
|
|
|
rphash = hashlib.new('ripemd160') |
59
|
|
|
rphash.update(binascii.unhexlify(sh2)) |
60
|
|
|
rp1 = rphash.hexdigest() |
61
|
|
|
return '0F02' + rp1 |
62
|
|
|
|
63
|
|
|
|
64
|
|
|
def sha_digest(hexastring): |
65
|
|
|
return hashlib.sha256(binascii.unhexlify(hexastring)).hexdigest() |
66
|
|
|
|
67
|
|
|
|
68
|
|
|
def compress_key(bts): |
69
|
|
|
intval = int(bts, 16) |
70
|
|
|
prefix = find_prefix(intval) |
71
|
|
|
return prefix + bts[0:64].decode("utf-8") |
72
|
|
|
|
73
|
|
|
|
74
|
|
|
def find_prefix(intval): |
75
|
|
|
if(intval % 2 == 0): |
76
|
|
|
prefix = '02' |
77
|
|
|
else: |
78
|
|
|
prefix = '03' |
79
|
|
|
return prefix |
80
|
|
|
|