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')