使用python解决数字签名的完整代码
时间: 2024-10-25 22:05:58 浏览: 32
(纯算法,没有调用库)python实现RSA数字签名代码、ppt、文档.rar
5星 · 资源好评率100%
Python中有多种库可以处理数字签名,比如`cryptography`库,它是一个用于加密、解密、哈希等操作的强大工具。下面是一个简单的示例,展示如何使用`cryptography`库实现消息摘要(HMAC)和RSA数字签名:
```python
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
# 定义一个函数来生成私钥和公钥
def generate_keys(password):
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b'salt',
iterations=100000,
backend=default_backend()
)
key = kdf.derive(password.encode())
private_key = serialization.load_der_private_key(
b'-----BEGIN PRIVATE KEY-----\n' + key + b'\n-----END PRIVATE KEY-----\n',
password=password.encode(),
backend=default_backend()
)
public_key = private_key.public_key()
return private_key, public_key
# 生成一对密钥对
password = b'secret_password'
private_key, public_key = generate_keys(password)
# 消息内容
message = 'Hello, this is an example message.'
# 对消息计算HMAC签名
hmac_signature = private_key.sign(
message.encode(), # 编码为字节串
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
# 对消息进行RSA签名
rsa_signature = private_key.sign(
message.encode(), # 同样编码为字节串
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
# 显示签名结果
print(f"HMAC Signature: {hmac_signature.hex()}")
print(f"RSA Signature: {rsa_signature.hex()}")
# 验证签名
is_valid_hmac = private_key.verify(
hmac_signature,
message.encode(),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
is_valid_rsa = public_key.verify(
rsa_signature,
message.encode(),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=padding.PSS.MAX_LENGTH
),
hashes.SHA256()
)
if is_valid_hmac and is_valid_rsa:
print("Signature validation successful.")
else:
print("Signature validation failed.")
阅读全文