Makalone LOgman
Makalone LOgman

Reputation: 980

OpenSSL AES Segmentation Fault on Encrypt Update

I have string with set size and trying to AES encrypt it, but I get Segmentation Fault at EVP_EncryptUpdate

size_t dec_len = 20;
char *dec = malloc(dec_len + 1);

//Fill dec
...
//Encrypt

EVP_CIPHER_CTX *ctx;
ctx = EVP_CIPHER_CTX_new();
unsigned char *key = (unsigned char *)" no ";
EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, &key, NULL);
EVP_CIPHER_CTX_set_padding(ctx, 0);
unsigned char *ciphertext;
int ciphertext_len;
EVP_EncryptUpdate(ctx, ciphertext, &ciphertext_len, dec, dec_len);
EVP_EncryptFinal_ex(ctx, ciphertext + ciphertext_len, &ciphertext_len);
EVP_CIPHER_CTX_free(ctx);

I have no idea what's causing this. Thank you.

Upvotes: 0

Views: 740

Answers (2)

Makalone LOgman
Makalone LOgman

Reputation: 980

Solved by allocating ciphertext variable.

Upvotes: 0

Andrew Henle
Andrew Henle

Reputation: 1

Per the OpenSSL documentation, is declared as

int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
    ENGINE *impl, const unsigned char *key, const unsigned char *iv);

Note that key is declared to be const unsigned char *key.

But your code is

unsigned char *key = (unsigned char *)" no ";
EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, &key, NULL);

You are passing the address of your key pointer to the function - an unsigned char ** instead of a const unsigned char *. You want to pass the address of the string, which is what key points to:

const unsigned char *key = (const unsigned char *)" no ";
EVP_EncryptInit_ex(ctx, EVP_aes_128_ecb(), NULL, key, NULL);

Upvotes: 1

Related Questions