在Python中,对文本文件进行加密和解密可以通过多种方式实现,以下是使用`cryptography`库进行AES加密和解密的示例代码:
加密文件
```python
from cryptography.fernet import Fernet
def encrypt_file(file_path, key):
生成密钥
key = Fernet.generate_key()
创建加密器
cipher = Fernet(key)
读取文件内容
with open(file_path, 'rb') as file:
file_content = file.read()
加密文件内容
encrypted_content = cipher.encrypt(file_content)
将加密后的内容写入新文件
encrypted_file_path = file_path + '.enc'
with open(encrypted_file_path, 'wb') as encrypted_file:
encrypted_file.write(encrypted_content)
解密文件```pythonfrom cryptography.fernet import Fernet
def decrypt_file(file_path, key):
创建加密器
cipher = Fernet(key)
读取加密文件内容
with open(file_path, 'rb') as file:
encrypted_content = file.read()
解密文件内容
decrypted_content = cipher.decrypt(encrypted_content)
将解密后的内容写入新文件
decrypted_file_path = file_path.replace('.enc', '')
with open(decrypted_file_path, 'wb') as decrypted_file:
decrypted_file.write(decrypted_content)

使用示例
```python
加密文件
encrypt_file('plain.txt', 'your_secret_key')
解密文件
decrypt_file('plain.txt.enc', 'your_secret_key')
请确保在使用前已经安装了`cryptography`库,可以通过以下命令安装:```pip install cryptography
以上代码示例展示了如何使用`cryptography`库中的`Fernet`类进行AES加密和解密操作。使用相同密钥对文件内容进行加密后,将加密内容保存到一个新的文件中,并以`.enc`扩展名标记。解密时,使用相同的密钥对加密文件进行解密,恢复原始文件内容。
需要注意的是,密钥的管理非常重要,确保密钥的安全存储和传输,以防加密内容被未授权访问。
