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

解说

要使⽤Python进⾏⽂件的加密和解密,可以使⽤第三⽅加密库,如cryptography或pycryptodome。
⼀个基本的⽰例,演⽰如何使⽤cryptography库对⽂件进⾏加密和解密:

  1. 安装cryptography库:
pip install cryptography

在这里插入图片描述

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

演练

第一步:创建要加密的文件
在这里插入图片描述

第二步:运行加密

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)

在这里插入图片描述
第三步:出现加密成功的文件
在这里插入图片描述

第四步:运行解密脚本

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)

在这里插入图片描述
第五步:生成解密的文件
在这里插入图片描述

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fo安方

觉得俺的文章还行,感谢打赏,爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值