Ошибка сегментации в EVP_CIPHER_CTX_new() при использовании OpenSSL в C

Я новичок в библиотеке OpenSSL на C, но работал над кодом для шифрования с использованием библиотек, принимая парольную фразу в качестве входных данных и генерируя соль, 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() был тем, кто ругался. Я сейчас в своем уме, пытаясь отладить его, и могу очень ценить некоторую помощь.

Заранее спасибо.


person Ashwin_Mathew    schedule 11.04.2015    source источник


Ответы (1)


Это неправильно:

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

char *pasphrase - это просто указатель на неизвестное место.

Измените это на:

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