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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
from random import randrange, choice
def judgePrimeNumber(num): sqrtResult = int(num ** 0.5) for i in range(2, sqrtResult + 1): if num % i == 0: return False return True
def judgeCoPrime(a, b): def maxCommonFactor(m, n): result = 0 while m % n > 0: result = m % n m = n n = result return result if maxCommonFactor(a, b) == 1: return True return False
def getPrimitiveRoot(primeNumber): primeList = [] primitiveRootList = [] for i in range(1, primeNumber): if judgeCoPrime(i, primeNumber): primeList.append(i) for i in primeList: tmpList = [] for j in range(1, len(primeList) + 1): tmpList.append(i ** j % primeNumber) tmpList.sort() if primeList == tmpList: primitiveRootList.append(i) return primitiveRootList
def createPubKey(primeNumber, primitiveRoot, randNum1, randNum2): pubKey1 = primitiveRoot ** randNum1 % primeNumber pubKey2 = primitiveRoot ** randNum2 % primeNumber return pubKey1, pubKey2
def createSubKey(primeNumber, pubKey1, pubKey2, randNum1, randNum2): subKey1 = pubKey2 ** randNum1 % primeNumber subKey2 = pubKey1 ** randNum2 % primeNumber return subKey1, subKey2
if __name__ == "__main__": print("—————Diffie-Hellman密钥交换—————") while True: primeNumber = int(input("输入共同素数:")) if judgePrimeNumber(primeNumber): break randNum1 = randrange(primeNumber) randNum2 = randrange(primeNumber) print("A随机数:", randNum1, "\nB随机数:", randNum2) primitiveRootList = getPrimitiveRoot(primeNumber) primitiveRoot = choice(primitiveRootList) print("所有本原根:", primitiveRootList) print("本次的本原根:", primitiveRoot) pubKey1, pubKey2 = createPubKey(primeNumber, primitiveRoot, randNum1, randNum2) print("A公钥:", pubKey1, "\nB公钥:", pubKey2) subKey1, subKey2 = createSubKey(primeNumber, pubKey1, pubKey2, randNum1, randNum2) if subKey1 == subKey2: print("AB共同会话密钥:", subKey1)
|