python rsa对txt进行加密解密
时间: 2023-05-27 13:01:23 浏览: 146
下面是Python的RSA加密和解密示例:
```python
# 导入库
import rsa
# 生成密钥对
(pubkey, privkey) = rsa.newkeys(1024)
# 显示公钥和私钥
print(pubkey)
print(privkey)
# 加密文本
message = b"Hello world"
ciphertext = rsa.encrypt(message, pubkey)
# 显示密文
print(ciphertext)
# 解密文本
plaintext = rsa.decrypt(ciphertext, privkey)
# 显示明文
print(plaintext)
```
以上代码会生成一个1024位的RSA密钥对并显示出来。然后对文本进行加密并显示出密文,再对密文进行解密并显示出明文。
注意:如果你想从.txt文件中读取文本并加密,可以使用以下代码:
```python
# 读取明文
with open("plaintext.txt", "rb") as f:
message = f.read()
# 加密文本
ciphertext = rsa.encrypt(message, pubkey)
# 保存密文
with open("ciphertext.txt", "wb") as f:
f.write(ciphertext)
```
解密也是类似的:
```python
# 读取密文
with open("ciphertext.txt", "rb") as f:
ciphertext = f.read()
# 解密文本
plaintext = rsa.decrypt(ciphertext, privkey)
# 保存明文
with open("plaintext.txt", "wb") as f:
f.write(plaintext)
```
希望这样可以帮助到你!
阅读全文
相关推荐

















