簡體   English   中英

openssl 解密 function 不能正常工作

[英]openssl decrypt function doesn't work correctly

我通過查看 wikiopenssl 編寫了這個 function,當我嘗試在 main func 中使用它時它工作正常。 然后我又寫了一個 function 來拿腳本來解密。 這是我的 function:

std::string ofxLibcrypto::decrypt(std::string ciphertext) {

unsigned char *plaintext;
unsigned char *binarytobedecrypted;

hex2stream(ciphertext, ciphertext);

for(int i = 0; i < ciphertext.length(); i++){
    binarytobedecrypted[i] = ciphertext[i];
}

int lenplaintext = decrypt(binarytobedecrypted, strlen((char*)binarytobedecrypted), k, v, plaintext);

std::string str(reinterpret_cast<char*>(plaintext));

clean();

ofLogVerbose("ofxLibcrypto.cpp") << "decrypted";

return str.substr(0, lenplaintext);
}

hex2stream 是一個 function 將base16字符串解碼為二進制並且工作正常。 第一個參數是要解碼的字符串,第二個參數是保存二進制值。 我看到問題出在解密函數中,這是解密函數:

int ofxLibcrypto::decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key, unsigned char *iv, unsigned char *plaintext) {

EVP_CIPHER_CTX *ctx;
int len;
int plaintext_len;

if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
ofLogNotice("IDB") << "To detect 1";

if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_128_cbc(), NULL, key, iv)) handleErrors();
ofLogNotice("IDB") << "To detect 2";

if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len)) handleErrors();
ofLogNotice("IDB") << "To detect 3";

plaintext_len = len;
ofLogNotice("IDB") << "To detect 4";

if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
ofLogNotice("IDB") << "To detect 5";

plaintext_len += len;
ofLogNotice("IDB") << "To detect 6";

EVP_CIPHER_CTX_free(ctx);
ofLogNotice("IDB") << "To detect 7";

return plaintext_len;
}

LogNotices 用於檢測問題出在哪里,它會打印出“檢測 4”,然后應用程序崩潰。 我嘗試了很多來解決,但我找不到解決方案。 已經謝謝大家了。

plaintext未初始化。 因此,它指向垃圾 memory。 EVP_DecryptUpdate寫入時,也就是未定義的行為。

此外,您也忘記分配binarytobedecrypted

做這個。 已經很晚了,但我猜你應該給明文一些額外的填充,無論你的加密算法使用什么塊大小。

binarytobedecrypted = new unsigned char[ciphertext.size()+1];
plaintext = new unsigned char[(ciphertext.size() + 128];

如果您認為該數據是“字符串”,請確保 null 在寫入緩沖區后終止。

if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len))
{
    handleErrors();
}
else
{
    plaintext[len] = '\0';
}
ofLogNotice("IDB") << "To detect 5";

我將解密 function 更改為:

std::string ofxLibcrypto::decrypt(std::string ciphertext) {
unsigned char empty[] = { 0 };
unsigned char *plaintext = empty;
hex2stream(ciphertext, ciphertext);
int lenplaintext = decrypt((unsigned char *)ciphertext.c_str(), 
(int)ciphertext.length(), k, v, plaintext);
std::string str(reinterpret_cast<char*>(plaintext));
clean();
ofLogVerbose("ofxLibcrypto.cpp") << "decrypted";

return str.substr(0, lenplaintext);
}

在此之后,同樣的問題再次發生,但我發現問題是純文本的 - 加密的文本 - 長度。 它適用於> 24個字符。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM