在 C 中使用 OpenSSL 时 EVP_CIPHER_CTX_new() 中的分段错误

Segmentation fault in EVP_CIPHER_CTX_new() when using OpenSSL in C

我完全是 C 中 OpenSSL 库的初学者,但我正在编写代码以使用库进行加密,同时将密码短语作为输入并从密码短语生成 salt、IV 和密钥。这是我到目前为止尝试过的:

int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *ciphertext)
{
char *passphrase;
printf("\nEnter a Pass Phrase:");
scanf("%s",passphrase);

ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
OPENSSL_config(NULL);

EVP_CIPHER_CTX *ctx;
const EVP_CIPHER *cipher;
const EVP_MD *dgst = NULL;
unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
const char *salt;

int len;

int ciphertext_len;

/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) //This line causes the error
    handleErrors();
cipher = EVP_get_cipherbyname("aes-256-cbc");
if(!cipher) { fprintf(stderr, "no such cipher\n"); return -1; }
dgst=EVP_get_digestbyname("md5");
if(!dgst) { fprintf(stderr, "no such digest\n"); return -1; }

if(!EVP_BytesToKey(cipher, dgst, salt, (unsigned char *) passphrase, strlen(passphrase), 1, key, iv))
{
    fprintf(stderr, "EVP_BytesToKey failed\n");
    return -1;
}

/* Initialise the encryption operation. IMPORTANT - ensure you use a key
* and IV size appropriate for your cipher
* In this example we are using 256 bit AES (i.e. a 256 bit key). The
* IV size for *most* modes is the same as the block size. For AES this
* is 128 bits */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
handleErrors();

/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;

/* Finalise the encryption. Further ciphertext bytes may be written at
* this stage.
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;

/* Clean up */
EVP_CIPHER_CTX_free(ctx);
EVP_cleanup();
ERR_free_strings();

return ciphertext_len;
}

我试过了,但一直出现分段错误。我试图调试并发现 EVP_CIPHER_CTX_new() 是那个诅咒它的人。我现在无能为力,正在尝试调试它,非常感谢您的帮助。

提前致谢。

这是不正确的:

char *passphrase;
printf("\nEnter a Pass Phrase:");
scanf("%s",passphrase);

char *pasphrase 只是指向未知位置的指针。

将其更改为:

char passphrase[2048];
printf("\nEnter a Pass Phrase:");
scanf("%s", passphrase);