python rsa 解密
时间: 2023-02-16 12:27:56 浏览: 109
python rsa 加密解密
RSA是一种非对称加密算法,在Python中可以使用pycryptodome库来进行RSA的加密和解密操作。具体的使用方法如下:
1. 安装pycryptodome库: `pip install pycryptodome`
2. 生成RSA密钥对:
```
from Crypto.PublicKey import RSA
# 生成密钥对
key = RSA.generate(2048)
# 保存公钥
with open('public.pem', 'wb') as f:
f.write(key.publickey().export_key())
# 保存私钥
with open('private.pem', 'wb') as f:
f.write(key.export_key())
```
3. 加密:
```
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 从文件中读取公钥
with open('public.pem', 'rb') as f:
key = RSA.import_key(f.read())
# 初始化加密器
cipher = PKCS1_OAEP.new(key)
# 需要加密的明文
plaintext = b'my plaintext'
# 加密
ciphertext = cipher.encrypt(plaintext)
```
4. 解密:
```
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
# 从文件中读取私钥
with open('private.pem', 'rb') as f:
key = RSA.import_key(f.read())
# 初始化解密器
cipher = PKCS1_OAEP.new(key)
# 解密
plaintext = cipher.decrypt(ciphertext)
```
希望这个能帮到你!
阅读全文