效果
代碼
from encryption_algorithm import Primitive_root, Euclid
import random
import math
def is_primer(n: int)-> bool:
return False if 0 in [n % i for i in range(2, int(math.sqrt(n))+1)] else True
def get_randint_primer(high: int, low=0)-> int:
R = random.randint(low, high)
while(is_primer(R)==False):
R = random.randint(low, high)
return R
def get_e(E_n):
euc = Euclid.euclid()
e = get_randint_primer(low=1, high=E_n)
while(euc.gcd(E_n,e)!=1):
e = get_randint_primer(low=1, high=E_n)
return e
def get_d(E_n,e):
d = 1
while(e*d%E_n!=1):
d += 1
return d
def encrypt(e,n,m):
return m**e%n
def decrypt(d,n,c):
return c**d%n
if __name__=='__main__':
p = get_randint_primer(low=200, high=400)
q = get_randint_primer(low=400, high=600)
n = p * q
E_n = Primitive_root.Euler(n)
e = get_e(E_n)
d = get_d(E_n,e)
m = 11
c = encrypt(e,n,m)
m_ = decrypt(d,n,c)
print('初始明文:%s'%(m))
print('加密密文:%s'%(c))
print('解密明文:%s'%(m_))