我想对神经网络的体系结构进行加密,以便保护研究的知识财产。
其中一个文件的示例与this示例具有相似的结构。
代码可以编译,但是出现了我不知道如何解决的运行时错误。错误消息是数字信封程序:EVP_DecryptFinal_ex:最终块长度错误。
我正在使用OpenSSL版本1.1.1a 2018年11月20日
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
std::ifstream in_file(file_name, std::ios::binary);
in_file.seekg(0, in_file.end);
long size = in_file.tellg();
in_file.seekg(0, in_file.beg);
std::vector<unsigned char> binarydata(size);
in_file.read((char*)binarydata.data(), size);
in_file.close();
EVP_CIPHER_CTX *en;
en = EVP_CIPHER_CTX_new();
unsigned char *salt = (unsigned char *)"12345678";
unsigned char *key_data = (unsigned char *)"super_secret_key_with_32_charact";
int k_len = strlen((const char*)key_data);
int nrounds = 5;
unsigned char key[32], iv[32];
EVP_BytesToKey(
EVP_aes_256_cbc(), EVP_sha1(),
salt,
key_data, k_len, nrounds,
key, iv);
EVP_CIPHER_CTX_init(en);
// I don't know why, but all examples that I have founded,
// calls this function twice, so I am doing it too.
EVP_EncryptInit_ex(en, EVP_aes_256_cbc(), NULL, key, iv);
EVP_EncryptInit_ex(en, NULL, NULL, NULL, NULL);
int c_len = size + AES_BLOCK_SIZE, f_len = 0;
std::vector<unsigned char> ciphertext(c_len);
EVP_EncryptUpdate(en, ciphertext.data(), &c_len, binarydata.data(), size);
EVP_EncryptFinal_ex(en, ciphertext.data()+c_len, &f_len);
EVP_CIPHER_CTX_free(en)
std::ofstream out_file(output_file, std::ios::binary);
out_file.write((char*)ciphertext.data(), ciphertext.size() *
sizeof(char));
out_file.close();
std::ifstream in_file(file_name, std::ios::binary);
in_file.seekg(0, in_file.end);
int size = in_file.tellg();
in_file.seekg(0, in_file.beg);
std::vector<unsigned char> ciphertext(size);
in_file.read((char*)ciphertext.data(), size);
in_file.close();
EVP_CIPHER_CTX *de;
de = EVP_CIPHER_CTX_new();
unsigned char *salt = (unsigned char *)"12345";
unsigned char *key_data = (unsigned char *)"super_secret_key_with_32_charact";
int k_len = strlen((const char*)key_data);
int nrounds = 5;
unsigned char key[32], iv[32];
EVP_BytesToKey(
EVP_aes_256_cbc(), EVP_sha1(),
salt,
key_data, k_len, nrounds,
key, iv)
EVP_CIPHER_CTX_init(de);
// I don't know why, but all examples that I have founded,
// calls this function twice, so I am doing it too.
EVP_DecryptInit_ex(de, EVP_aes_256_cbc(), NULL, key, iv);
EVP_DecryptInit_ex(de, NULL, NULL, NULL, NULL);
int p_len = size, f_len = 0;
std::vector<unsigned char> plaintext(p_len);
EVP_DecryptUpdate(de, plaintext.data(), &p_len, ciphertext.data(), size);
EVP_DecryptFinal_ex(de, plaintext.data()+p_len, &f_len);
EVP_CIPHER_CTX_free(de);
return plaintext;
我想对如何解决此问题有所帮助。
答案 0 :(得分:0)
我不知道这是否仍然是一个问题。 我遇到了完全相同的问题,并通过加密后调整密文的长度来解决了这个问题:
EVP_EncryptFinal_ex(en, ciphertext.data()+c_len, &f_len);
ciphertext.erase(ciphertext.begin() + c_len + f_len, ciphertext.end());
以此,密文的长度应为n * AES_BLOCK_SIZE。