python文件加密

这篇博客介绍了如何使用Python的cryptography模块来加密和解密神经网络模型文件。首先,通过Fernet生成加密密钥并保存,然后读取密钥以加密模型文件,并将加密内容保存。最后,通过相同的密钥解密文件,恢复原始模型内容。这种方法为敏感的神经网络模型提供了安全性。
摘要由CSDN通过智能技术生成

参考了

神经网络模型如何加密 (Python) - 哔哩哔哩

 实现方法

一、安装工具

安装cryptography模块

pip install cryptography -i https://pypi.tuna.tsinghua.edu.cn/simple

二、测试加密

加密代码chenjiami.py 

1、生成加密key并保存

from cryptography.fernet import Fernet

#-----------------------------------------------------------
#(1)生成的秘钥,注意保存,第一次
key = Fernet.generate_key()
print(key)
file = open('D:/00testjiami/key.data', 'wb')
file.write(key)
file.close()

2、读取key

fr = open("D:/00testjiami/key.data", 'rb')
chenkey = fr.read()
print(chenkey)

3、将文件加密并保存

#(3)加密文件
fpwd = Fernet(chenkey)
file_orign =open("D:/00testjiami/xxxxx.model", 'rb')
file_content= file_orign.read()
print("chenread")
encrypted_content = fpwd.encrypt(file_content)

fsave =open("D:/chenyolo/00testjiami/chenmodel.data", 'wb')
fsave.write(encrypted_content)
print("jia mi 完成")

4、解密文件并获取内容

#(4)解密文件
fpwd = Fernet(chenkey)
file_jiemi_orign =open("D:/chenyolo/00testjiami/chenmodel.data", 'rb')
file_jiemi_content= bytearray(fpwd.decrypt(file_jiemi_orign.read()))

fsave_jiemi =open("D:/chenyolo/00testjiami/chenmodeljiemi.pt", 'wb')
fsave_jiemi.write(file_jiemi_content)
print("jie mi 完成")

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值