python利⽤ SHA1withRSA 算法对得到的需加密明⽂进⾏签名得到签名 sig,同时写出相应的解密操作
时间: 2023-11-03 17:08:19 浏览: 231
下面是使用 SHA1withRSA 算法进行签名和解密的 Python 代码:
```python
import hashlib
import base64
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA1
from Crypto.PublicKey import RSA
# 生成RSA密钥对
key = RSA.generate(2048)
# 获取私钥和公钥
private_key = key.export_key()
public_key = key.publickey().export_key()
# 需加密明文
message = 'Hello, world!'
# 对明文进行 SHA1 摘要
message_digest = hashlib.sha1(message.encode()).digest()
# 使用私钥对摘要进行签名
signature = pkcs1_15.new(RSA.import_key(private_key)).sign(SHA1.new(message_digest))
# 将签名进行 Base64 编码
sig = base64.b64encode(signature)
# 解码签名并使用公钥进行验签
sig = base64.b64decode(sig)
try:
pkcs1_15.new(RSA.import_key(public_key)).verify(SHA1.new(message_digest), sig)
print("Signature is valid.")
except (ValueError, TypeError):
print("Signature is invalid.")
# 使用公钥对签名进行解密
decrypted_signature = pkcs1_15.new(RSA.import_key(public_key)).decrypt(sig, None)
# 将解密后的签名与原始摘要进行比较
if decrypted_signature == message_digest:
print("Signature decryption is successful.")
else:
print("Signature decryption is unsuccessful.")
```
需要注意的是,此处使用了 PyCryptodome 库中的 RSA 模块进行加密和解密操作。在代码中,我们首先使用 RSA.generate() 方法生成了一个 2048 位的 RSA 密钥对,然后将其分别导出为私钥和公钥。接着,我们对需要加密的明文进行 SHA1 摘要,并使用私钥对摘要进行签名。签名完成后,我们使用 Base64 对其进行编码,并将其作为签名 sig 进行存储和传输。
在验签时,我们首先将 sig 进行 Base64 解码,并使用公钥对其进行验签。如果验签成功,则说明签名是有效的。接着,我们使用公钥对 sig 进行解密,并将解密后的签名与原始摘要进行比较。如果两者相等,则说明解密操作成功。
阅读全文
相关推荐


















