mister
mister

Reputation: 3433

How to decrypt data without plaintext size? - openssl encryption c++ ubuntu environment

I have the following function that decrypts ciphertexts.

However i have a problem that i would like to decrypt the data without having the plaintext length! How do i do that? As if i send a encrypted data over, it would not be appropriate to send the ciphertext with the plain-text length.

int main()
{
/*some code*/
char input[] = "123456789abcdef";
int olen, len;
len = strlen(input)+1;

plaintext = (char *)aes_decrypt(&de, ciphertext, &len);
/*some code*/
}

Decryption method

unsigned char *aes_decrypt(EVP_CIPHER_CTX *e, unsigned char *ciphertext, int *len)
    {
      /* plaintext will always be equal to or lesser than length of ciphertext*/
      int p_len = *len, f_len = 0;
      unsigned char *plaintext = (unsigned char *)malloc(p_len);

      if(!EVP_DecryptInit_ex(e, NULL, NULL, NULL, NULL)){
        printf("ERROR in EVP_DecryptInit_ex \n");
        return NULL;
      }

      if(!EVP_DecryptUpdate(e, plaintext, &p_len, ciphertext, *len)){
        printf("ERROR in EVP_DecryptUpdate\n");
        return NULL;
      }

      if(!EVP_DecryptFinal_ex(e, plaintext+p_len, &f_len)){
        printf("ERROR in EVP_DecryptFinal_ex\n");
        return NULL;
      }

      *len = p_len + f_len;
      return plaintext;
    }

Thanks in advance!! :)

Upvotes: 0

Views: 1623

Answers (2)

Simon Richter
Simon Richter

Reputation: 29578

Typically you would prefix the cleartext with a length indicator before encryption. This can be as small as a single byte "valid bytes in last block".

Upvotes: 1

atomicinf
atomicinf

Reputation: 3736

You don't actually need the plaintext length - just the length of the ciphertext.

EVP can perform and handle PKCS #7 padding 'automagically', and does this by default. PKCS #7 padding works as follows: it determines how many characters of padding are needed to block-align the plaintext for encryption, and then takes that number and repeats it at the end of the plaintext that many times (in byte form).

For instance, if I have a 14-byte block of plaintext of the hexadecimal form

61 74 74 61 63 6b 20 61 74 20 64 61 77 6e

and I need to pad it to 16 bytes for encryption, I will append 02 twice to the end to get

61 74 74 61 63 6b 20 61 74 20 64 61 77 6e 02 02

If my plaintext is already aligned to a 16-byte boundary, then I add 16 bytes of 10 (i.e. 16 in hex) to the end of the plaintext. I can thus always assume that padding exists in the plaintext, removing my need to guess. EVP's routines will detect the padding after decryption and trim it off, returning the original plaintext with its correct length.

Upvotes: 4

Related Questions