dh代码 python
时间: 2025-01-02 19:16:43 浏览: 6
### 实现Diffie-Hellman算法
Diffie-Hellman密钥交换协议允许双方在公共信道上安全地建立共享秘密[^1]。以下是该算法的一个简单Python实现:
```python
import random
def generate_large_prime():
"""生成大素数"""
from sympy import nextprime
return nextprime(random.randint(2**31, 2**32))
def modular_exponentiation(base, exponent, modulus):
"""模幂运算,即计算 (base^exponent) % modulus"""
result = pow(base, exponent, modulus)
return result
class DiffieHellman:
def __init__(self, generator=None, prime_modulus=None):
self.generator = generator or 2
self.prime_modulus = prime_modulus or generate_large_prime()
self.private_key = random.randint(2, self.prime_modulus - 2)
def get_public_key(self):
"""生成并返回公钥"""
public_key = modular_exponentiation(
base=self.generator,
exponent=self.private_key,
modulus=self.prime_modulus
)
return public_key
def compute_shared_secret(self, other_party_public_key):
"""利用对方的公钥来计算共享的秘密值"""
shared_secret = modular_exponentiation(
base=other_party_public_key,
exponent=self.private_key,
modulus=self.prime_modulus
)
return shared_secret
# 测试代码如下:
alice = DiffieHellman(generator=5, prime_modulus=23)
bob = DiffieHellman(generator=5, prime_modulus=23)
print(f"Alice 的私钥: {alice.private_key}")
print(f"Bob 的私钥: {bob.private_key}")
public_key_alice = alice.get_public_key()
public_key_bob = bob.get_public_key()
shared_secret_alice = alice.compute_shared_secret(public_key_bob)
shared_secret_bob = bob.compute_shared_secret(public_key_alice)
if shared_secret_alice == shared_secret_bob:
print("成功建立了相同的共享秘钥!")
else:
print("未能建立相同共享秘钥.")
```
此段代码展示了如何创建两个`DiffieHellman`对象分别代表Alice和Bob,并通过交换各自的公钥最终达成一致的共享秘密。
阅读全文