深度学习模型加密(pytorch,onnx,darknet)

文章目录

*
更新时间
环境
流程介绍
代码(onnx,darknet)
代码(pytorch)
参考文章

更新时间

最近更新: 2022-09

环境

Python 3.8
opencv 4.5.2.54
onnxruntime 1.10.0
pytorch 1.10.2
cryptography 3.1.1

流程介绍

加密:

  1. 模型以二进制存储
  2. 以二进制形式读取
  3. 用cryptography对文件加密
  4. 保存加密后文件

解密:

  1. 读取加密文件
  2. 使用cryptography解密
  3. 转换为框架可读数据

代码(onnx,darknet)


from cryptography.fernet import Fernet

key = Fernet.generate_key()

print(key)

f = Fernet(key)

model_file = ['./yolov4-tiny.weights','./yolov4-tiny.cfg','./yolov4-tiny.onnx']

new_model_file = ['./yolov4-tiny.dll','./yolov4-tiny-cfg.dll','./yolov4-tiny-onnx.dll']

for i in range(2):

    with open(new_model_file[i],'wb') as ew:

        content = open(model_file[i],'rb').read()

        encrypted_content = f.encrypt(content)

        ew.write(encrypted_content)

import cv2

conf_file = open(new_model_file[1],'rb').read()

conf_file = f.decrypt(conf_file)

conf_file   = bytearray(conf_file)

weight_flie = open(new_model_file[0],'rb').read()
weight_flie = f.decrypt(weight_flie)
weight_flie = bytearray(weight_flie)

net = cv2.dnn.readNetFromDarknet(conf_file,weight_flie)
print(net)

import onnxruntime

onnx_file = open(new_model_file[2],'rb').read()
onnx_file = f.decrypt(onnx_file)

session = onnxruntime.InferenceSession(onnx_file)
print(session)

代码(pytorch)


from cryptography.fernet import Fernet

key = Fernet.generate_key()

print(key)

f = Fernet(key)

import io
import torch

model = torch.load('./model.pth',map_location='cpu')

byte = io.BytesIO()
torch.save(model, byte)
byte.seek(0)

pth_bytes = byte.read()

new_model = f.encrypt(pth_bytes)

with open('new_model.pth', 'wb') as fw:
    fw.write(new_model)

with open('new_model.pth', 'rb') as fr:
    new_model = fr.read()

new_model = f.decrypt(new_model)

model_byte = io.BytesIO(new_model)
model_byte.seek(0)

model = torch.load(model_byte)

print(model)

参考文章

Pytorch模型加密的方法
神经网络如何加密(Python)

Original: https://blog.csdn.net/djj199301111/article/details/126708162
Author: 炼丹去了
Title: 深度学习模型加密(pytorch,onnx,darknet)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/708635/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球