import hashlib from crypto_func import def main init parameters 65537

 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
import hashlib
from crypto_func import *
def main():
# init parameters
e = 65537
p = generate_prime_number(128) # Miller-Rabin
q = generate_prime_number(128) # Miller-Rabin
n = p * q
phi = (p - 1) * (q - 1)
d = modinv(e, phi)
print("Parameters:\n\tp = {}\n\tq = {}".format(p, q))
print("\tn = {}".format(n))
print("\te = {}\n\td = {}".format(e, d))
# generate message
m = id_generator()
print("Message:\n\t{}".format(m))
# sign
m_hash = hashlib.md5(m.encode()).hexdigest()
m_hash_int = int_from_bytes(bytearray.fromhex(m_hash))
sign_m = pow(m_hash_int, d, n)
print("\tsign(m) = {}".format(sign_m))
# encrypt message
c = pow(int_from_bytes(m.encode()), e, n)
print("Encrypt[message]:\n\t{}".format(hex(c)))
# decrypt message
m_enc = pow(c, d, n)
print("Decrypt[message]:\n\t{}".format(int_to_bytes(m_enc).decode()))
# check sign
m_enc_hash = hashlib.md5(int_to_bytes(m_enc)).hexdigest()
m_enc_hash_int = int_from_bytes(bytearray.fromhex(m_enc_hash))
sign_m_enc = pow(sign_m, e, n)
print("\tcheck_sign(m) = {}".format(hex(sign_m_enc)[2:]))
if __name__ in '__main__':
main()