cencryptionaesmbed

How does decryption work in mbedtls?


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 );
}

Solution

  • 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.