nRF9160: AES-128 CBC decryption does not work with MbedTLS (but encryption does work)

I am trying to get AES-128 CBC decryption to work on the nRF9160 using the MbedTLS library in my bare metal application. I am linking with the following libraries found in sdk-nrfxlib-2.2.0 in their cortex-m33, hard-float, no-interrupts versions:

libnrf_cc310_platform_0.9.16.a

libnrf_cc310_core_0.9.16.a

libnrf_cc310_legacy_crypto_0.9.16.a

I am executing the crypto-related code in secure mode.

After initializing an AES context, and setting the 128-bit key for the context, I am calling mbedtls_aes_crypt_cbc to encrypt and decrypt data, using a 128-bit initialization vector.

So, while encryption (with the mode parameter set to MBEDTLS_AES_ENCRYPT) works just fine, as long as the length is a multiple of the blocksize (16 bytes), decryption using the same function, but with mode set to MBEDTLS_AES_DECRYPT does not. It always returns error -34 (-0x022) which is the error code for MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH, even when the length is actually a multiple of 16 bytes. Only when the length is 0, it returns 0 (no error) - but then it does not decrypt anything, of course.

So, is there a bug in the AES-128 CBC decryption algorithm in the CC310 version of MbedTLS or am I missing something?

By the way, I have also tested SHA-256 digest and ECDSA secp256r1 sign and verify. The SHA-256 algorithm seems to produce wrong results when updating with more than 64 bytes at a time (why?). ECDSA seems to work just fine, but the functions for manipulating big numbers (mpi) are not compiled into any of the libraries listed above, which is irritating, since I then have to manually compile and link with individual .c files from the MbedTLS library.

Thanks in advance :-)

Parents Reply Children
  • Thank you very much, Kazi :-)

    Turns out it is not a bug, I simply overlooked that the context has separate functions for setting encryption and decryption keys.

    If MbedTLS had implemented a different error code for "key not set", I might have caught this error sooner.

    Interestingly, I cannot set both keys at once before using the context to encrypt/decrypt data. If I do that, the decryption will return 0, but produces garbage instead of the correct output. However, if I call mbedtls_aes_setkey_dec() just before the decryption operation, on the same context as I used for encryption, it works just fine. Care has to be taken.

    I guess the best way to do it, is to use separate contexts for encryption and decryption, as you recommended.

    Thanks again :-)

Related