在大多数项目交付场景中,经常需要对部署模型进行加密。模型加密一方面可以防止泄密,一方面可以便于模型跟踪管理,防止混淆。
由于博主使用的部署模型多为TensorRT格式,这里以TensorRT模型为例,讲解如何对模型进行加密、解密以及推理加密模型。
Crypto++ 是C/C++的加密算法库,基本上涵盖了市面上的各类加密解密算法,包括对称加密算法(AES等)和非对称加密算法(RSA等)。
两种算法使用的场景不同,非对称加密算法一般应用于数字签名和密钥协商的场景下,而对称加密算法一般应用于纯数据加密场景,性能更优。在对模型的加密过程中使用对称加密算法。
以AES-GCM加密模式为例,编写一个检测的加密、解密方法
std::string Encrypt(const std::string &data, const CryptoPP::SecByteBlock &key, const CryptoPP::SecByteBlock &iv) {
std::string cipher;
try {
CryptoPP::GCM<:aes>::Encryption e;
e.SetKeyWithIV(key, key.size(), iv, iv.size());
CryptoPP::StringSource(data, true,
new CryptoPP::AuthenticatedEncryptionFilter(e,
new CryptoPP::StringSink(cipher)
) // StreamTransformationFilter
); // StringSource
}
catch(const CryptoPP::Exception& e) {
std::cerr ::Decryption d;
d.SetKeyWithIV(key, key.size(), iv, iv.size());
// The StreamTransformationFilter removes
// padding as required.
CryptoPP::StringSource(cipher, true,
new CryptoPP::AuthenticatedDecryptionFilter(d,
new CryptoPP::StringSink(recovered)
) // StreamTransformationFilter
); // StringSource
}
catch(const CryptoPP::Exception& e) {
std::cerr
上述代码,使用AES-CBC加密模式对数据进行加密、解密,其中key和iv为加密算法的参数,keySize为key的长度。
加密流程:
解密流程:
推理加密模型的方法有两种,一种是将模型解密后保存为文件再进行推理,另一种是将模型解密后转换为序列化格式,再进行推理。
很明显第一种方式比较鸡肋,因为每次推理都需要进行解密,而且解密后的模型文件也会暴露在外面,不安全。这里使用第二种方式,将模型解密后转换为序列化格式进行推理。这里给出一个简单的例子,将存储解密数据的字符串recovered进行序列化。
std::vector Convert2TRTengine(const std::string& data) {
unsigned char* engine_data[1];
engine_data[0] = new unsigned char[data.length() + 1];
std::copy(data.begin(), data.end(), engine_data[0]);
engine_data[0][data.length()] = '
登录查看全部
参与评论
手机查看
返回顶部