写一个RSA签名验签工具代码
时间: 2024-02-05 16:13:07 浏览: 33
以下是一个简单的RSA签名验签工具代码,使用Python的PyCrypto库实现:
```python
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA256
# 生成RSA密钥对
key = RSA.generate(2048)
# 获取私钥和公钥
private_key = key.export_key()
public_key = key.publickey().export_key()
# 签名函数
def sign(message, private_key):
key = RSA.import_key(private_key)
h = SHA256.new(message)
signer = PKCS1_v1_5.new(key)
signature = signer.sign(h)
return signature
# 验签函数
def verify(message, signature, public_key):
key = RSA.import_key(public_key)
h = SHA256.new(message)
verifier = PKCS1_v1_5.new(key)
return verifier.verify(h, signature)
# 测试签名和验签
message = b'This is a message to be signed'
signature = sign(message, private_key)
print('Signature:', signature.hex())
result = verify(message, signature, public_key)
print('Verification result:', result)
```
需要注意的是,在实际使用中,私钥应该保密保存,而公钥可以公开传播。签名方使用私钥对消息进行签名,验签方使用公钥对收到的消息和签名进行验证。如果验证成功,则表明消息确实是由签名方发送的,并且在传输过程中没有被篡改。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)