[英]SIMPLE OpenSSL RSA Encryption in C/C++ is causing me headaches
求助:我很傻。 加密的第一個參數應該是key.size(),解密的第一個參數應該是RSA_size(myKey)。
大家好,我在弄清楚如何執行此操作時遇到了一些麻煩。
基本上,我只希望客戶端和服務器能夠互相發送加密的消息。
這將是極度不安全的,因為我正試圖解決所有問題,所以我不妨從底層開始。
到目前為止,我已經使用了所有的密鑰,但是加密/解密使我陷入了困境。
首先,我要使用C ++,但是其中大多數功能都需要C字符串,因此我所做的任何事情都可能導致問題。
請注意,在客戶端,我收到有關解密的以下錯誤。
error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed
我不太了解填充的工作原理,所以不知道如何解決。
此處的任何一方都是相關變量,后跟代碼。
客戶:
RSA *myKey; // Loaded with private key
// The below will hold the decrypted message
unsigned char* decrypted = (unsigned char*) malloc(RSA_size(myKey));
/* The below holds the encrypted string received over the network.
Originally held in a C-string but C strings never work for me and scare me
so I put it in a C++ string */
string encrypted;
// The reinterpret_cast line was to get rid of an error message.
// Maybe the cause of one of my problems?
if(RSA_private_decrypt(sizeof(encrypted.c_str()), reinterpret_cast<const unsigned char*>(encrypted.c_str()), decrypted, myKey, RSA_PKCS1_OAEP_PADDING)==-1)
{
cout << "Private decryption failed" << endl;
ERR_error_string(ERR_peek_last_error(), errBuf);
printf("Error: %s\n", errBuf);
free(decrypted);
exit(1);
}
服務器:
RSA *pkey; // Holds the client's public key
string key; // Holds a session key I want to encrypt and send
//The below will hold the encrypted message
unsigned char *encrypted = (unsigned char*)malloc(RSA_size(pkey));
// The reinterpret_cast line was to get rid of an error message.
// Maybe the cause of one of my problems?
if(RSA_public_encrypt(sizeof(key.c_str()), reinterpret_cast<const unsigned char*>(key.c_str()), encrypted, pkey, RSA_PKCS1_OAEP_PADDING)==-1)
{
cout << "Public encryption failed" << endl;
ERR_error_string(ERR_peek_last_error(), errBuf);
printf("Error: %s\n", errBuf);
free(encrypted);
exit(1);
}
讓我再說一次,以防萬一,我知道我的代碼很爛,但是我只是想建立一個框架來理解這一點。
很抱歉,這冒犯了您的資深編碼員。
預先感謝你們提供的任何幫助!
可能不是唯一的問題,但是: RAS_xxxcrypt
函數的第一個參數是緩沖區的字節數。 sizeof(key.c_str())
不產生key中的字節數,它產生key.c_str()
結果類型的sizeof(const char*)
,即sizeof(const char*)
。 您可能希望改為傳遞字符串中的字符數,這可以通過size()
成員函數獲得。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.