verify.py
1.69 KB
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
import os
from getmac import get_mac_address
from datetime import datetime
from Crypto.PublicKey import RSA
from consts import PUBLIC_KEY_NAME, CERT_NAME, SPLIT_CHAR, DEFAULT_MAC
def get_exponent_and_modulus(public_key_path):
with open(public_key_path, 'r') as public_fp:
public_key = RSA.import_key(public_fp.read())
return public_key.e, public_key.n
def get_signature(cert_path):
with open(cert_path, 'r') as fp:
signature = fp.read()
return int(signature)
def is_expire(expire_date_str):
expire_date = datetime.strptime(expire_date_str, '%Y-%m-%d')
if datetime.today() >= expire_date:
return True
return False
def is_valid_mac(mac):
if mac == DEFAULT_MAC:
return True
if mac == get_mac_address():
return True
return False
def verify(public_key_path, cert_path):
try:
e, n = get_exponent_and_modulus(public_key_path)
signature = get_signature(cert_path)
encrypt_int = pow(signature, e, n)
encrypt_str = encrypt_int.to_bytes(length=encrypt_int.bit_length() // 8 + 1, byteorder='big').decode()
mac, _, expire_date_str = encrypt_str.split(SPLIT_CHAR)
if is_expire(expire_date_str) or not is_valid_mac(mac):
return False
return True
except Exception as e:
print('verify error: {0}'.format(e))
return False
if __name__ == '__main__':
base_dir = os.path.dirname(os.path.abspath(__file__))
public_key_path = os.path.join(base_dir, PUBLIC_KEY_NAME)
cert_path = os.path.join(base_dir, CERT_NAME)
is_valid = verify(public_key_path, cert_path)
if is_valid:
print('verify success')
else:
print('verify failed')