DH秘钥交换协议
2018-04-22 本文已影响0人
AnswerHua
DH秘钥交换协议
实现思路
参考:这里
具体步骤
- 这个协议使用一个质数p的整数模n乘法群以及其原根g
- Alice与Bob协定使用 p以及base g
- Alice选择一个秘密整数a, 计算A = g**a mod p并发送给Bob。
- Bob选择一个秘密整数b, 计算B = g**b mod p并发送给Alice。
- Alice计算alice_key = B a mod p
- Bob计算bob_key = A b mod p
下面贴出代码
import random
import math
from random import choice
def getRandomPrime(Nmax):
isPrime = [0]*(Nmax+1)
primeList = []
isPrime[2] = 1
for i in range(3,Nmax,2):
isPrime[i] = 1
for i in range(3,int(math.sqrt((Nmax+1)))+1,2):
if(isPrime[i] == 1):
for j in range(i*i,Nmax+1,2*i):
isPrime[j] = 0
for i in range(2,Nmax+1):
if (isPrime[i]==1):
primeList.append(i)
p , q = random.sample(primeList,2)
return p
#根据原根的性质求质数de原根
def getPrimaryRoot(p):
a = 2
while True:
mark = 0
if a ** (p - 1) % p == 1:
num = 2
while num < p - 1:
if a ** num % p == 1:
mark = 1
num += 1
if mark == 0:
return a
a += 1
def getA_B(g,a,p):
return (g ** a) % p
def getKey(A_B,a_b,p):
return (A_B**a_b) % p
if __name__ == "__main__":
p = getRandomPrime(200)
g = getPrimaryRoot(p)
rand_a = random.randint(0, p - 1)
A = getA_B(g, rand_a, p)
rand_b = random.randint(0, p - 1)
B = getA_B(g, rand_b, p)
alice_key = getKey(B,rand_a,p)
bob_key = getKey(A,rand_b,p)
print("step1: ","a:",rand_a," ","g:",g," ","p:",p)
print("step2: ", "A:", A)
print("step3: ", "B:", B)
print("step4: ", "Alice_key:", alice_key)
print("step5: ", "Bob_key:", bob_key)
下面贴出运行截图
运行截图