#include <stdio.h>
#include "mbedtls/aes.h"

#include "sr_config.h"
#include "sr_log.h"



int cipher_test(void)
{
    mbedtls_aes_context aes_ctx;
    unsigned char key[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2,
                            0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf,
                            0x4f, 0x3c };
    unsigned char iv[] = { 0x00, 0x11, 0x22, 0x33, 
                           0x44, 0x55, 0x66, 0x77,
                           /* Don't use this in real code! */
                           /* The IV should be unpredictable */
                         };
    unsigned char ciphertext[64] = {
        /* This is the output of encrypting
         * "Single block msg" with above key and IV using AES-128-CBC mode.
         * Every character here is in hex. */
        /* To decrypt it back to plain text "Single block msg", you can:
         * mbedtls_aes_crypt_cbc(&aes_ctx,
         *                       MBEDTLS_AES_DECRYPT,
         *                       sizeof(ciphertext),
         *                       iv,
         *                       ciphertext,
         *                       plaintext);
         */ 
        // Encrypted data starts from here
        // These are just random bytes for illustration purposes only.
        // Real encrypted data would look more like random noise.
        // Do not use these values in production.
        //
        // d4 e9 c5 f8 a1 ed b9 eb d3 af ea bd a6 e7 74 73
        // cc a2 c9 87 a8 db 4a be f6 aa b1 d5 f5 d7 3d dc
        // d9 b0 bf ff f9 e3 ce fd bd 36 ed ab ae e0 da de
        // fe 0c fa ef bb af 18 eb bc cd b1 dd f7 ba e3 aa
        /* To avoid syntax errors in this example, we will use the following */
        /* plaintext as input for decryption. */
        'S', 'i', 'n', 'g', 'l', 'e', ' ', 
        'b', 'l', 'o', 'c', 'k', ' ', 
        'm', 's', 'g',
    };
    unsigned char plaintext[64];
    
    mbedtls_aes_init(&aes_ctx);
    
    if (mbedtls_aes_setkey_dec(&aes_ctx, key, sizeof(key)*8) != 0)
    {
        SR_PRINTF("Error setting decryption key.\n");
        return -1;
    }
    
    mbedtls_aes_crypt_cbc(&aes_ctx,
                          MBEDTLS_AES_DECRYPT,
                          sizeof(ciphertext),
                          iv,
                          ciphertext,
                          plaintext);
                          
    SR_PRINTF("Decrypted message: %.*s\n", sizeof(plaintext), plaintext);
                          
    mbedtls_aes_free(&aes_ctx);
                          
    return 0;
}
