This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts
This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

How do I encrypt a string?

Hello.
We are developing using nrf52832 (S132 v7.0.1, SDK v17.0.0).

I'm looking at how to encrypt a string with AES CBC.
Below is the code we are considering.

static uint8_t m_key[16] = {'N', 'O', 'R', 'D', 'I', 'C', 'A', 'E', 'S', 'C', 'B', 'C', 'T', 'E', 'S', 'T'};
static char m_plain_text[NRF_CRYPTO_EXAMPLE_AES_MAX_TEXT_SIZE] =
{
    "Example string to demonstrate basic usage of AES CBC mode."
};
static char m_encrypted_text[NRF_CRYPTO_EXAMPLE_AES_MAX_TEXT_SIZE];

static void crypto_test(void){
    static nrf_crypto_aes_context_t cbc_encr_ctx;
    static nrf_crypto_aes_context_t cbc_decr_ctx;
           ret_code_t               ret_val;
           uint8_t                  iv[NRF_CRYPTO_MBEDTLS_AES_IV_SIZE];  // 16
           size_t                   len_in;
           size_t                   len_out;

    memset(m_encrypted_text, 0, sizeof(m_encrypted_text));
    memset(m_decrypted_text, 0, sizeof(m_decrypted_text));
    memset(iv, 0, sizeof(iv));

    len_in = strlen(m_plain_text);
    len_out = sizeof(m_encrypted_text);

    ret_val = nrf_crypto_init();
    APP_ERROR_CHECK(ret_val);

    ret_val = nrf_crypto_aes_init(&cbc_encr_ctx, &g_nrf_crypto_aes_cbc_128_info, NRF_CRYPTO_ENCRYPT);
    AES_ERROR_CHECK(ret_val);

    ret_val = nrf_crypto_aes_key_set(&cbc_encr_ctx, m_key);
    AES_ERROR_CHECK(ret_val);

    ret_val = nrf_crypto_aes_iv_set(&cbc_encr_ctx, iv);
    AES_ERROR_CHECK(ret_val);

    ret_val = nrf_crypto_aes_finalize(&cbc_encr_ctx,
                                      (uint8_t *)m_plain_text,
                                      len_in,
                                      (uint8_t *)m_encrypted_text,
                                      &len_out);
    AES_ERROR_CHECK(ret_val);

    return;
}

Currently, it works, but the strings are not encrypted and are all "0x00".
How can I solve it?

Best Regards.

Related