文章目錄
效果
代碼
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))