Python加密文件导到另外一个文件
作者:野牛程序员:2023-08-12 12:05:36python阅读 2782
可以使用Python中的加密库来加密文件,并将加密后的内容导出到另一个文件。以下是使用cryptography库的示例代码,演示如何对文件进行AES加密,并将加密后的内容导出到另一个文件。首先,确保已经安装了cryptography库:
pip install cryptography
然后,可以使用以下示例代码:
from cryptography.fernet import Fernet
# 生成随机密钥
key = Fernet.generate_key()
# 初始化Fernet对象
cipher_suite = Fernet(key)
# 指定输入文件和输出文件
input_file_path = 'path/to/your/input/file'
output_file_path = 'path/to/your/output/encrypted/file'
# 读取输入文件内容
with open(input_file_path, 'rb') as input_file:
input_data = input_file.read()
# 加密数据
encrypted_data = cipher_suite.encrypt(input_data)
# 将加密数据写入输出文件
with open(output_file_path, 'wb') as output_file:
output_file.write(encrypted_data)
print("File encrypted and saved.")在上面的代码中,将path/to/your/input/file替换为要加密的实际输入文件的路径,将path/to/your/output/encrypted/file替换为加密后的输出文件的路径。
请注意,此示例仅使用AES加密文件内容,而密钥是使用Fernet算法生成的。需要确保在解密文件时使用正确的密钥。加密和解密之间的密钥必须相同。在实际应用中,需要妥善保管密钥,并考虑更复杂的安全措施。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892

- 上一篇:python批量重命名文件名
- 下一篇:arduino 定时器与定时中断的使用
