python实现RSA加解密及实例
时间: 2023-07-31 14:09:06 浏览: 60
RSA是一种非对称加密算法,用于保护信息在网络上的传输安全。RSA算法的安全性基于大数分解问题,即一个大数能否被分解成两个较小的质数的乘积。以下是Python实现RSA加解密的示例代码:
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
# 生成RSA密钥对
key = RSA.generate(1024)
# 获取公钥和私钥
private_key = key.export_key()
public_key = key.publickey().export_key()
# 将公钥和私钥保存到文件中
with open('private.pem', 'wb') as f:
f.write(private_key)
with open('public.pem', 'wb') as f:
f.write(public_key)
# 加密
def rsa_encrypt(message, public_key):
rsa_key = RSA.import_key(public_key)
cipher = PKCS1_v1_5.new(rsa_key)
ciphertext = cipher.encrypt(message.encode(encoding='utf-8'))
return base64.b64encode(ciphertext).decode()
# 解密
def rsa_decrypt(ciphertext, private_key):
rsa_key = RSA.import_key(private_key)
cipher = PKCS1_v1_5.new(rsa_key)
message = cipher.decrypt(base64.b64decode(ciphertext), None)
return message.decode()
# 测试加解密
message = 'hello world'
ciphertext = rsa_encrypt(message, public_key)
print('加密后:', ciphertext)
plaintext = rsa_decrypt(ciphertext, private_key)
print('解密后:', plaintext)
```
在上面的代码中,首先使用RSA.generate()生成一个RSA密钥对,然后将公钥和私钥保存到文件中,接着定义了rsa_encrypt()和rsa_decrypt()函数分别用于加密和解密。最后通过测试加解密函数验证了算法的正确性。