椭圆曲线加密算法python代码实现
时间: 2024-11-14 20:05:05 浏览: 4
椭圆曲线密码学(Elliptic Curve Cryptography, ECDH 或 ECC)是一种基于数学难题的公钥密码体制,它的安全性来自于椭圆曲线上的点运算。在Python中,我们可以利用像`cryptography`这样的库来实现ECC。
以下是一个简单的Python代码示例,展示如何使用`cryptography`库创建一个ECC密钥对,并进行加密解密:
```python
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.utils import (
encode_dsa_signature,
decode_dsa_signature,
)
# 创建椭圆曲线实例
curve = ec.SECP256R1()
# 生成随机私钥和公共密钥
private_key = ec.generate_private_key(curve)
public_key = private_key.public_key()
# 将公钥转化为PEM格式便于传输
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo,
)
# 加密消息
def encrypt(message, public_pem):
shared_secret = private_key.exchange(ec.ECDH(), bytes.fromhex(public_pem))
encrypted = shared_secret.to_bytes(32, 'big') # 假设消息长度小于32字节
return encrypted
# 解密消息
def decrypt(encrypted, private_key_pem):
private_key = serialization.load_pem_private_key(private_key_pem, password=None)
shared_secret = private_key.exchange(ec.ECDH(), encrypted)
decrypted = shared_secret.to_bytes(32, 'big')
return decrypted.decode('utf-8')
# 示例
message = "Hello, ECDH!"
encrypted_msg = encrypt(message.encode(), public_pem.hex())
print("Encrypted:", encrypted_msg)
decrypted_msg = decrypt(bytes.fromhex(encrypted_msg), private_key_pem.hex())
print("Decrypted:", decrypted_msg)
阅读全文