PT文件加密解密

PT文件加密解密

加密形式

在这里插入图片描述

from cryptography.fernet import Fernet

# 密钥生成后自行以安全方式保存
key = Fernet.generate_key()
f = Fernet(key)

# 保存解码密钥
file = open('C:/Users/ps/Desktop/key.txt','w')
file.write(str(key.decode('utf-8')))

# 未加密文件
origin_files = [r"C:\Users\ps\Desktop\best.pt"]

# 加密后的文件
encrypted_files = ['C:/Users/ps/Desktop/yolov5s-en.data']

# 加密
for i in range(len(origin_files)):
    with open(encrypted_files[i],'wb') as ew:
        content = open(origin_files[i],'rb').read()
        encrypted_content = f.encrypt(content)
        ew.write(encrypted_content)




from cryptography.fernet import Fernet

# 读取密钥
with open('C:/Users/ps/Desktop/key.txt', 'rb') as key:
    key = key.readline()
f = Fernet(key)

# 加密文件
encrypted_files = ['C:/Users/ps/Desktop/yolov5s-en.data']

# 解密文件
decrypt_files = ['C:/Users/ps/Desktop/yolov5s-de.pt']

# 解密
for i in range(len(encrypted_files)):
    with open(decrypt_files[i],'wb') as ew:
        content = open(encrypted_files[i],'rb').read()
        decrypt_content = f.decrypt(content)
        ew.write(decrypt_content)

另一种方式

        k = key.encode('utf-8')
        iv = iv.encode('utf-8')

        # Encrypt
        def Encrypt(byte_string):
            cryptos = AES.new(k, mode, iv)
            pad_pkcs7 = pad(byte_string, AES.block_size, style='pkcs7')  # 选择pkcs7补全
            cipher_text = cryptos.encrypt(pad_pkcs7)
            # 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
            return b2a_hex(cipher_text)

        w1 = str(f).split('\\')[-1]
        w2 = w1.split('.')[0]
        w3 = str(f).split('b')[0]

        new_name = [w3 + GetFileName(w2, w3)] #新建的文件名字,这里是代码需要自己创建的一个函数
        ff = [f] # 读取的pt或者onnx
        for i in range(len(ff)):
            with open(new_name[i], 'wb') as f1:
                cont = open(ff[i], 'rb').read()
                encrypted = Encrypt(cont)

                f1.write(encrypted)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值