DH算法实现加密解密代码
时间: 2024-06-11 10:03:18 浏览: 127
Diffie-Hellman (DH)算法是一种非对称加密算法,用于在两个通信方之间共享密钥,而无需事先共享任何秘密信息。这个过程基于数学原理,特别是大数素数和离散对数问题。以下是一个简单的DH算法实现(Python版本):
```python
from Crypto.PublicKey import DHPublicKey
from Crypto.Random import get_random_bytes
from Crypto.Cipher import PKCS1_OAEP
# 生成一个安全的大素数p和一个相对应的g值
def generate_keys(p, g):
generator = g
prime = p
# Alice的私钥部分
alice_private_key = get_random_bytes(20)
# Alice的公钥部分
alice_public_key = DHPublicKey(generator=generator, key_material=alice_private_key, p=prime)
# Bob的私钥部分(类似生成)
bob_private_key = get_random_bytes(20)
# Bob的公钥部分
bob_public_key = DHPublicKey(generator=generator, key_material=bob_private_key, p=prime)
return (alice_private_key, alice_public_key), (bob_private_key, bob_public_key)
# 使用Alice的公钥计算共享密钥
def compute_shared_secret(alice_private_key, bob_public_key):
shared_key = alice_private_key * bob_public_key
return shared_key
# Alice和Bob相互交换公钥后
alice_keys, bob_keys = generate_keys(2**16 + 1, 5)
alice_shared_secret = compute_shared_secret(alice_keys, bob_keys)
bob_shared_secret = compute_shared_secret(bob_keys[0], alice_keys)
# 对明文进行加密
def encrypt(message, shared_secret, cipher):
ciphertext = cipher.encrypt(message)
return ciphertext
# 对密文进行解密
def decrypt(ciphertext, shared_secret, cipher):
plaintext = cipher.decrypt(ciphertext)
return plaintext
# 示例:使用共享密钥进行加密和解密
alice_cipher = PKCS1_OAEP.new(alice_shared_secret)
bob_cipher = PKCS1_OAEP.new(bob_shared_secret)
message = "This is a secret message"
encrypted_message = encrypt(message, alice_shared_secret, alice_cipher)
decrypted_message = decrypt(encrypted_message, bob_shared_secret, bob_cipher)
print("Original Message:", message)
print("Encrypted Message:", encrypted_message)
print("Decrypted Message:", decrypted_message)
```
阅读全文