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

时间:2015-04-11 10:11:19

标签: c openssl evp-cipher

我是C语言中的OpenSSL库的初学者,但正在研究使用库加密的代码,同时将密码短语作为输入并从密码短语生成salt,IV和key。这就是我到现在为止所尝试的:

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()是一个诅咒它的人。我现在正在努力调试它并且真的很感激一些帮助。

提前致谢。

1 个答案:

答案 0 :(得分:1)

这是不正确的:

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

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

将其更改为:

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