# 代码

``````from encryption_algorithm import Primitive_root
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
# 获取q、a
def get_QA(size_q: list):
q = get_randint_primer(low=size_q[0],high=size_q[1])
a = Primitive_root.Primitive_root(q)
while(len(a)==0):
q = get_randint_primer(low=size_q[0],high=size_q[1])
a = Primitive_root.Primitive_root(q)
return q, a
# 单向陷门计算
# a^Pow mod n 计算
def calc_Key(a, Pow, n):
return int(pow(a, Pow))%n
if __name__=='__main__':
# q范围
size_q = [5000,10000]
# q、a确定
q, a_lt = get_QA(size_q)
a = a_lt[1]
# 私钥确定
Xa = random.randint(1, q)
Xb = random.randint(1, q)
# 公钥计算并发布
Ya = calc_Key(a,Xa,q)
Yb = calc_Key(a,Xb,q)
# 共享密钥计算
Share_a = calc_Key(Yb,Xa,q)
Share_b = calc_Key(Ya,Xb,q)
print('用户a计算出的共享密钥: {}'.format(Share_a))
print('用户b计算出的共享密钥: {}'.format(Share_b))
``````