rsa加密算法python
时间: 2023-11-18 13:57:12 浏览: 115
基于python的非对称加密算法rsa
RSA是一种非对称加密算法,用于加密的密钥和用于解密的密钥不是同一个。RSA可以根据密钥的大小改变分组大小,如果加密的数据不是分组大小的整数倍,则会根据具体的应用方式增加额外的填充位。在Python中,可以使用Crypto库实现RSA加密算法。具体实现过程包括生成公钥和私钥,加密数据和解密数据,签名和解签等步骤。可以参考以下代码实现RSA加密算法:
```python
from Crypto import Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
# 生成随机偏移量
random_generator = Random.new().read
# 生成一个私钥
rsa = RSA.generate(2048, random_generator)
# 导出私钥
private_key = rsa.exportKey()
# 生成私钥所对应的公钥
public_key = rsa.publickey().exportKey()
# 将私钥内容写入文件中
with open('rsa_private_key.pem', 'wb')as f:
f.write(private_key)
# 将公钥内容写入文件中
with open('rsa_public_key.pem', 'wb')as f:
f.write(public_key)
# 加密数据
message = 'Hello, world!'
with open('rsa_public_key.pem', 'rb') as f:
key = f.read()
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = cipher.encrypt(message.encode())
# 解密数据
with open('rsa_private_key.pem', 'rb') as f:
key = f.read()
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
text = cipher.decrypt(cipher_text, random_generator)
# 签名
with open('rsa_private_key.pem', 'rb') as f:
key = f.read()
rsakey = RSA.importKey(key)
signer = Signature_pkcs1_v1_5.new(rsakey)
digest = SHA.new()
digest.update(message.encode())
sign = signer.sign(digest)
# 验证签名
with open('rsa_public_key.pem', 'rb') as f:
key = f.read()
rsakey = RSA.importKey(key)
verifier = Signature_pkcs1_v1_5.new(rsakey)
digest = SHA.new()
digest.update(message.encode())
is_verify = verifier.verify(digest, sign)
print('加密后的数据:', cipher_text)
print('解密后的数据:', text.decode())
print('签名:', sign)
print('验证签名结果:', is_verify)
```
阅读全文