python-自动化篇-办公-文件-加解密

解说

要使⽤Python进⾏⽂件的加密和解密,可以使⽤第三⽅加密库,如cryptography或pycryptodome。

⼀个基本的⽰例,演⽰如何使⽤cryptography库对⽂件进⾏加密和解密:

  1. 安装cryptography库:
python 复制代码
pip install cryptography
  1. ⽂件加密:
python 复制代码
from cryptography.fernet import Fernet 

# ⽣成加密密钥 
key = Fernet.generate_key() 
cipher_suite = Fernet(key) 

# 读取要加密的⽂件 
with open('plain_file.txt', 'rb') as file: 
	plain_text = file.read()

# 加密⽂件内容 
cipher_text = cipher_suite.encrypt(plain_text) 

# 将加密后的内容写⼊⽂件 
with open('encrypted_file.txt', 'wb') as file: 
	file.write(cipher_text) 

# 保存密钥⽤于解密 
with open('encryption_key.key', 'wb') as key_file: 
	key_file.write(key)
  1. ⽂件解密:
python 复制代码
from cryptography.fernet import Fernet 

# 从⽂件中加载密钥 
with open('encryption_key.key', 'rb') as key_file: 
	key = key_file.read() 

cipher_suite = Fernet(key) 

# 读取要解密的⽂件 
with open('encrypted_file.txt', 'rb') as file: 
	cipher_text = file.read() 

# 解密⽂件内容 
plain_text = cipher_suite.decrypt(cipher_text) 

# 将解密后的内容写⼊⽂件 
with open('decrypted_file.txt', 'wb') as file: 
	file.write(plain_text)

在这个⽰例中,使⽤Fernet对⽂件进⾏加密和解密。⾸先,⽣成⼀个随机密钥,然后使⽤密钥对⽂件 内容进⾏加密。加密后的内容和密钥都保存在⽂件中。然后,使⽤相同的密钥来解密⽂件内容。 请注意,⽂件加密和解密需要妥善保管密钥,因为只有拥有正确密钥的⼈才能解密⽂件。密钥丢失后,⽂件将无法解密。因此,请确保密钥的安全存储。此外,⽂件加密和解密是敏感操作,需要小心处理,确保不会丢失任何数据。

演练

第一步:创建要加密的文件

第二步:运行加密

python 复制代码
from cryptography.fernet import Fernet 

# ⽣成加密密钥 
key = Fernet.generate_key() 
cipher_suite = Fernet(key) 

# 读取要加密的⽂件 
with open('plain_file.txt', 'rb') as file: 
	plain_text = file.read()

# 加密⽂件内容 
cipher_text = cipher_suite.encrypt(plain_text) 

# 将加密后的内容写⼊⽂件 
with open('encrypted_file.txt', 'wb') as file: 
	file.write(cipher_text) 

# 保存密钥⽤于解密 
with open('encryption_key.key', 'wb') as key_file: 
	key_file.write(key)

第三步:出现加密成功的文件

第四步:运行解密脚本

python 复制代码
from cryptography.fernet import Fernet 

# 从⽂件中加载密钥 
with open('encryption_key.key', 'rb') as key_file: 
	key = key_file.read() 

cipher_suite = Fernet(key) 

# 读取要解密的⽂件 
with open('encrypted_file.txt', 'rb') as file: 
	cipher_text = file.read() 

# 解密⽂件内容 
plain_text = cipher_suite.decrypt(cipher_text) 

# 将解密后的内容写⼊⽂件 
with open('decrypted_file.txt', 'wb') as file: 
	file.write(plain_text)

第五步:生成解密的文件

相关推荐
晚秋大魔王13 分钟前
OpenHarmony 开源鸿蒙南向开发——linux下使用make交叉编译第三方库——wget
java·linux·运维·开发语言·华为·harmonyos
heath ceTide16 分钟前
轻量、优雅、高扩展的事件驱动框架——Hibiscus-Signal
java·开发语言
_extraordinary_17 分钟前
Java 常用的Arrays函数
java·开发语言
_extraordinary_20 分钟前
Java 类和对象
java·开发语言
Aliano21724 分钟前
TestNGException ClassCastException SAXParserFactoryImpl是Java自带的Xerces解析器——解决办法
java·开发语言·python
漫谈网络28 分钟前
回调函数应用示例
开发语言·python·回调函数
亚林瓜子43 分钟前
pyenv简单的Python版本管理器(macOS版)
开发语言·python·macos·pyenv
夜松云44 分钟前
Qt信号槽机制与UI设计完全指南:从基础原理到实战应用
开发语言·qt·ui·qt designer·布局管理·参数传递·qt信号槽
青钰未央1 小时前
14、Python时间表示:Unix时间戳、毫秒微秒精度与time模块实战
python·改行学it
珂朵莉MM1 小时前
2024 睿抗机器人开发者大赛CAIP-编程技能赛-专科组(国赛)解题报告 | 珂学家
开发语言·人工智能·算法·leetcode·职场和发展·深度优先·图论