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