当想要分享模型权重给第三方使用时,可能并不想让对方直接可视onnx文件,故可以对此进行加密。Fernet是Cryptography包下的一个Python模块,它使用一个独特的密钥来加密和解密数据。Fernet实现了对称密钥加密技术,因为没有密钥就无法读取/修改数据。下面列出了Fernet模块中使用的各种元素。
参考:深入探究Python中的Fernet模块 - 掘金 (juejin.cn)
- 输入:{Plain_text (需要加密的数据),密钥(用于解密数据的唯一密钥),时间戳}
- 带有CBC模式的128位AES
- 填充
- 带有SHA256的HMAC
- 费尔内特令牌:输入文本的加密数据,以及密钥和时间戳。这个令牌为输入的文本提供必要的完整性和认证。
一、生成秘钥并对模型进行加密
from cryptography.fernet import Fernet
import onnxruntime
key = Fernet.generate_key()
f = Fernet(key)
print(key)
# 原始模型路径
origin_file = './model/model.onnx'
#加密模型
encrypted_file = './model/model.dll'
# 二进创建打开生成文件
with open(encrypted_file,'wb') as ew:
content = open(origin_file,'rb').read()
encrypted_content = f.encrypt(content)
ew.write(encrypted_content)
# 使用onnxruntime模块读取onnx模型测试
onnx_file = f.decrypt(open(encrypted_file,'rb').read())
# onnx不需要转换数据格式
session = onnxruntime.InferenceSession(onnx_file, providers=["CPUExecutionProvider"])
# print(session)
二、在其他位置加载模型
key = b'前文生成的秘钥key'
f = Fernet(key)
model_path = f.decrypt(open(args.model_path, 'rb').read())
session = onnxruntime.InferenceSession(model_path, providers=["CPUExecutionProvider"])
三、python文件加密
-
.pyc
加密 -
代码混淆加密
-
.pyd
/.so
加密
参考:如何防止你的代码被窃取?Python代码加密方案汇总(带实例验证)_from pytransform import get_user_data-CSDN博客