写出一段运用ECDH进行加解密的python代码
时间: 2023-07-23 13:09:14 浏览: 49
以下是一个简单的基于ECDH的加解密示例代码,使用了Python的cryptography库:
```python
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
# 生成ECDH密钥对
private_key = ec.generate_private_key(ec.SECP256R1())
public_key = private_key.public_key()
# 序列化公钥和私钥
private_key_bytes = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
public_key_bytes = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# 从公钥字节串反序列化出公钥对象
recipient_public_key = serialization.load_pem_public_key(
public_key_bytes,
backend=default_backend()
)
# 使用自己的私钥和对方的公钥生成共享密钥
shared_key = private_key.exchange(ec.ECDH(), recipient_public_key)
# 使用HKDF算法从共享密钥生成密钥和IV
hkdf = HKDF(
algorithm=hashes.SHA256(),
length=32 + 16,
salt=None,
info=b'encryption and iv',
backend=default_backend()
)
key_and_iv = hkdf.derive(shared_key)
# 分离出密钥和IV
key = key_and_iv[:32]
iv = key_and_iv[32:]
# 使用AES-CBC算法进行加密
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
plaintext = b'hello world!'
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plaintext) + encryptor.finalize()
# 使用AES-CBC算法进行解密
decryptor = cipher.decryptor()
decrypted_plaintext = decryptor.update(ciphertext) + decryptor.finalize()
assert decrypted_plaintext == plaintext
```
注意,此代码仅用于示例目的。在实际使用中,您需要考虑安全问题,并根据您的具体需求和环境进行适当的修改。