Python实现数字签名的完整代码
时间: 2024-10-25 09:05:38 浏览: 49
在Python中,数字签名通常通过哈希函数和公钥加密技术来实现,如RSA算法。下面是一个简单的示例,展示如何使用`cryptography`库来创建和验证数字签名:
```python
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric.utils import (
encode_dss_signature,
decode_dss_signature
)
# 生成密钥对(公钥和私钥)
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
public_key = private_key.public_key()
# 假设有一个需要签名的消息
message = b"This is a message to be signed"
# 使用私钥进行签名(HMAC-SHA256为例,这里也可以用RSA)
signer = private_key.signer(padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
))
signer.update(message)
signature = signer.finalize()
# 将签名转换为DER编码以便传输
signature_der = encode_dss_signature(signature, private_key.key_size)
# 验证签名
try:
verifier = public_key.verifier(
signature_der,
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
)
)
verifier.update(message)
verifier.verify()
print("Signature verified successfully.")
except Exception as e:
print(f"Signature verification failed: {e}")
阅读全文