我正在尝试使用 RSA 及其高级信封函数对 OpenSSL 进行公共加密。但是,我似乎无法理解它们,并且遇到了分段错误。我的项目中的这个精简代码重现了这个问题:
#include <iostream>
#include <string>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/rand.h>
int main()
{
EVP_CIPHER_CTX *rsaCtx;
rsaCtx = new EVP_CIPHER_CTX;
unsigned char *ek;
size_t ekl;
unsigned char *iv;
size_t ivl;
EVP_PKEY *keypair;
keypair = NULL;
EVP_CIPHER_CTX_init(rsaCtx);
EVP_PKEY_CTX *ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, NULL);
EVP_PKEY_keygen_init(ctx);
EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, 2048);
EVP_PKEY_keygen(ctx, &keypair);
EVP_PKEY_CTX_free(ctx);
ek = new unsigned char[EVP_PKEY_size(keypair)];
iv = new unsigned char[EVP_MAX_IV_LENGTH];
ivl = EVP_MAX_IV_LENGTH;
std::string cipherText;
std::string plainText = "A STRING";
size_t encMsgLen = 0;
size_t blockLen = 0;
EVP_SealInit(rsaCtx, EVP_aes_256_cbc(), &ek, (int*)ekl, iv, &keypair, 1);
EVP_SealUpdate(rsaCtx, (unsigned char*)cipherText.c_str() + encMsgLen, (int*)&blockLen, (const unsigned char*)plainText.c_str(), (int)plainText.size() + 1);
encMsgLen += blockLen;
EVP_SealFinal(rsaCtx, (unsigned char*)cipherText.c_str() + encMsgLen, (int*)&blockLen);
encMsgLen += blockLen;
EVP_CIPHER_CTX_cleanup(rsaCtx);
EVP_PKEY_free(keypair);
delete[] ek;
delete[] iv;
delete rsaCtx;
std::cout << cipherText;
return 0;
}
我在线路上遇到分段错误EVP_SealInit(rsaCtx, EVP_aes_256_cbc(), &ek, (int*)ekl, iv, &keypair, 1);
我究竟做错了什么?