5

I wrote the following simple encryption-decryption program using mbedtls library. Encryption works fine (checked against http://aes.online-domain-tools.com/). However, when decrypting back I get incorrect result (output2 and input are different). Am I misusing the lib?

int main()
{
    mbedtls_aes_context aes;
    mbedtls_aes_context aes2;

    unsigned char key[16] = "itzkbgulrcsjmnv";
    key[15] = 'x';

    unsigned char iv[16] = {0xb2, 0x4b, 0xf2, 0xf7, 0x7a, 0xc5, 0xec, 0x0c, 0x5e, 0x1f, 0x4d, 0xc1, 0xae, 0x46, 0x5e, 0x75};

    const unsigned char *input = (const unsigned char*) "Some string to b";
    unsigned char output[128] = {0};
    unsigned char output2[128] = {0};

    mbedtls_aes_setkey_enc( &aes, key, 16*8 );
    mbedtls_aes_crypt_cbc( &aes, MBEDTLS_AES_ENCRYPT, strlen((const char*)input), iv, input, output );

    mbedtls_aes_setkey_dec( &aes2, key, 16*8 );
    mbedtls_aes_crypt_cbc( &aes2, MBEDTLS_AES_DECRYPT, strlen((const char*)output), iv, output, output2 );
}
Kara
  • 6,115
  • 16
  • 50
  • 57
Sergey
  • 1,168
  • 2
  • 13
  • 28

2 Answers2

5

I believe that the mbedtls_aes_crypt_cbc() function will alter the initialisation vector as it works. If you expect the same value that was input, you will need to start with the same initialisation vector.

Jon Trauntvein
  • 4,453
  • 6
  • 39
  • 69
0

The function mbedtls_aes_crypt_cbc() modifies iv's value so that the second call of mbedtls_aes_crypt_cbc() does not use the same value. This explains the failure of the decryption.

int main()
{
    mbedtls_aes_context aes;
    mbedtls_aes_context aes2;

    unsigned char key[16] = "itzkbgulrcsjmnv";
    key[15] = 'x';

    unsigned char eiv[16] = {0xb2, 0x4b, 0xf2, 0xf7, 0x7a, 0xc5, 0xec, 0x0c, 0x5e, 0x1f, 0x4d, 0xc1, 0xae, 0x46, 0x5e, 0x75};
    unsigned char div[16] = {0xb2, 0x4b, 0xf2, 0xf7, 0x7a, 0xc5, 0xec, 0x0c, 0x5e, 0x1f, 0x4d, 0xc1, 0xae, 0x46, 0x5e, 0x75};

    const unsigned char *input = (const unsigned char*) "Some string to b";
    unsigned char output[128] = {0};
    unsigned char output2[128] = {0};

    mbedtls_aes_setkey_enc( &aes, key, 16*8 );
    mbedtls_aes_crypt_cbc( &aes, MBEDTLS_AES_ENCRYPT, strlen((const char*)input), eiv, input, output );

    mbedtls_aes_setkey_dec( &aes2, key, 16*8 );
    mbedtls_aes_crypt_cbc( &aes2, MBEDTLS_AES_DECRYPT, strlen((const char*)output), div, output, output2 );
}
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 12 '22 at 03:11