rsa算法加解密python
时间: 2023-11-20 17:57:01 浏览: 101
python的RSA加解密
5星 · 资源好评率100%
以下是使用Python实现RSA算法的加解密过程:
1.生成公钥和私钥
```python
from Crypto.PublicKey import RSA
# 生成密钥对
key = RSA.generate(2048)
# 获取公钥和私钥
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)
```
2.加密和解密
```python
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 加载公钥和私钥
with open('private.pem', 'rb') as f:
private_key = RSA.import_key(f.read())
with open('public.pem', 'rb') as f:
public_key = RSA.import_key(f.read())
# 加密
cipher = PKCS1_OAEP.new(public_key)
encrypted_data = cipher.encrypt(b'Hello, world!')
# 解密
cipher = PKCS1_OAEP.new(private_key)
decrypted_data = cipher.decrypt(encrypted_data)
print(decrypted_data.decode()) # 输出:Hello, world!
```
阅读全文