python 实现文件加密 源代码
时间: 2024-01-05 16:43:54 浏览: 45
可以使用 cryptography 库中的 Fernet 对称加密算法来实现文件的加密。以下是一个示例代码:
```python
from cryptography.fernet import Fernet
# 生成一个加密密钥
key = Fernet.generate_key()
# 将密钥保存到文件中
with open('key.txt', 'wb') as f:
f.write(key)
# 加载密钥
with open('key.txt', 'rb') as f:
key = f.read()
# 创建一个 Fernet 对象
f = Fernet(key)
# 加密文件
with open('plaintext.txt', 'rb') as plaintext:
with open('ciphertext.txt', 'wb') as ciphertext:
ciphertext.write(f.encrypt(plaintext.read()))
# 解密文件
with open('ciphertext.txt', 'rb') as ciphertext:
with open('decrypted.txt', 'wb') as plaintext:
plaintext.write(f.decrypt(ciphertext.read()))
```
这段代码将生成一个随机的密钥,并将密钥保存到文件中。然后可以使用该密钥来加密和解密文件。注意,密钥的保护非常重要,因为如果密钥泄露,加密的文件可以被解密。