python ecdh Crypto 加解密
时间: 2023-07-01 10:27:05 浏览: 56
ECDH (Elliptic Curve Diffie-Hellman) 是一种密钥交换协议,用于在两个通信方之间安全地协商共享密钥。然后,可以使用共享密钥进行加密或解密操作。
在 Python 中,可以使用 PyCryptodome 库实现 ECDH 和加解密操作。以下是一个示例代码:
```
from Crypto.Util.number import long_to_bytes
from Crypto.PublicKey import ECC
from Crypto.Cipher import AES
# 加密函数
def encrypt(plaintext, key):
cipher = AES.new(key, AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
return cipher.nonce, ciphertext, tag
# 解密函数
def decrypt(nonce, ciphertext, tag, key):
cipher = AES.new(key, AES.MODE_EAX, nonce)
plaintext = cipher.decrypt_and_verify(ciphertext, tag)
return plaintext
# 生成随机的 ECC 密钥对
private_key = ECC.generate(curve='P-256')
public_key = private_key.public_key()
# 将公钥发送给另一个通信方
# 另一个通信方收到公钥后
other_public_key = ECC.import_key('...')
# 计算共享密钥
shared_key = private_key.exchange(other_public_key.pointQ)
# 将共享密钥转换为字节数组
shared_key_bytes = long_to_bytes(shared_key, private_key.baselen)
# 使用共享密钥进行加密和解密操作
plaintext = b'This is a secret message.'
nonce, ciphertext, tag = encrypt(plaintext, shared_key_bytes)
decrypted_plaintext = decrypt(nonce, ciphertext, tag, shared_key_bytes)
print('Plaintext:', plaintext)
print('Decrypted plaintext:', decrypted_plaintext)
```
在这个示例代码中,我们先定义了一个加密函数和一个解密函数。然后,我们使用 ECDH 协议计算共享密钥,并将共享密钥转换为字节数组。最后,我们使用共享密钥对一个明文进行加密操作,并对密文进行解密操作。