【发布时间】:2015-03-25 13:20:01
【问题描述】:
我正在开发一个 google chrome NaCl 扩展,该扩展涉及使用 openssl 库函数对数据进行加密和解密。加密工作完美,解密目前也工作正常,但为此我不得不进行某种破解,但我不确定这是否是处理它的正确方法。
else if(action == "decryption")
{
pp::Var content = dict_message.Get("content");
//aes decryption starts here
pp::VarArrayBuffer buffer(content);
const char *password = "password";
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
int cipherlen = buffer.ByteLength();
int len = cipherlen + EVP_MAX_BLOCK_LENGTH;
unsigned char *plaintext = (unsigned char*)malloc(len*sizeof(unsigned char));
unsigned char* ciphertext = static_cast<unsigned char*>(buffer.Map());
aes_init(password, (int)strlen(password), key, iv);
len = decrypt(ciphertext, cipherlen, key, iv, plaintext);
buffer.Unmap();
plaintext[len]='\0'; //fix a bug of overshooting plaintext sent
//aes decryption ends here
pp::VarDictionary reply;
reply.Set("action","decryption");
reply.Set("plaintext", (char*)plaintext);
reply.Set("fileSize", len);
PostMessage(reply);
free(plaintext);
}
现在此代码解密数据并发送回扩展页面上的 javascript。请注意plaintext[len]='\0'; 行,如果我不放它,有时我会在plaintext 中正确解密的文本之后得到一个垃圾,这在我的javascript 中反映为null。那么处理这个错误的正确方法是什么?
【问题讨论】:
-
任何 c 风格字符串的结尾都需要有一个空终止符。如果您的解密方法没有将它放在字符串的末尾,那么您需要手动进行。
-
如果原始数据加密不包含终止空字符,解密数据也不会。因此,您必须提供一个。我的猜测是加密代码使用类似于
strlen()而不是strlen()+1的原始明文长度加密字符串。顺便说一句,您应该使用像std::vector<char> plaintext(len);这样的RAII 容器,而不是手动跳过malloc/free潜在火灾环。在malloc和free之间抛出的任何异常目前都保证会泄漏内存。
标签: c++ encryption google-chrome-extension openssl google-nativeclient