/*
 * Copyright (c) 2019-2023 Beijing Hanwei Innovation Technology Ltd. Co. and
 * its subsidiaries and affiliates (collectly called MKSEMI).
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into an MKSEMI
 *    integrated circuit in a product or a software update for such product,
 *    must reproduce the above copyright notice, this list of conditions and
 *    the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of MKSEMI nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without
 *    specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    MKSEMI integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be
 *    reverse engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY MKSEMI "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL MKSEMI OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "mk_aes.h"
#include "mk_trace.h"
#include "mk_reset.h"
#include "mk_calib.h"
#include "mk_wdt.h"
#include "libc_rom.h"
#include "board.h"

// Key: 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32 0x32

// 0123456789987654
static uint8_t ecb_input[16] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34};
static uint8_t ecb_cipher[16] = {0xCE, 0xA0, 0x69, 0x6A, 0xF8, 0xAE, 0xF4, 0x01, 0x83, 0x34, 0x42, 0xA0, 0x2F, 0x89, 0x07, 0x76};
static uint8_t ecb_output[16];

// plaintext: ABCDEFGHIJKLMNOP
static uint8_t cbc_input[16] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50};
static uint8_t cbc_iv[16] = {0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30};
static uint8_t cbc_cipher[16] = {0x9D, 0x53, 0xBB, 0xEF, 0x51, 0x0F, 0xEC, 0xD4, 0x4D, 0xC7, 0xAC, 0xD7, 0x94, 0x9F, 0xE7, 0x0D};
static uint8_t cbc_output[16];

// plaintext: ABCDEFGHIJKLMNOP
static uint8_t ctr_input[16] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50};
static uint8_t ctr_cipher[16] = {0xAF, 0xBC, 0x2F, 0xC0, 0xB8, 0xFB, 0x5E, 0x99, 0x7E, 0xC3, 0x19, 0x5E, 0xE8, 0xFF, 0x31, 0x32};
static uint8_t ctr_initial_counter[16] = {0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30};
static uint8_t ctr_output[16];

static uint8_t nonce[13] = {0xAC, 0xDE, 0x48, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x09, 0x05};
// additional authenticated data
static uint8_t auth_data[30] = {0x4A, 0xEF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x48, 0xDE, 0xAC, 0x01, 0x00, 0x00, 0x00, 0x00,
                                0x48, 0xDE, 0xAC, 0x0D, 0x09, 0x00, 0x00, 0x00, 0x01, 0x02, 0x0F, 0x01, 0x00, 0x80, 0x3F};
// Plaintext Data
static uint8_t plaintext_data[3] = {0x41, 0x43, 0x4B};

// AuthData = AddAuthData || PlaintextData
// sizeof(Authdata) >= sizeof(auth_data) + sizeof(plaintext_data) + 18
static uint8_t AuthData[60] = {0};

// Cipher Data||Encrypted Authentication Tag Data (Length of Tag-Data = mac_size)
static uint8_t cipher_data[] = {0x0B, 0xC7, 0x5A, 0xFE, 0x9f, 0xCF, 0xFB};

// output buffer
// Security level 5: ENC-MIC-32 ==> mac_size = 4
// Security level 6: ENC-MIC-64 ==> mac_size = 8
// Security level 7: ENC-MIC-128 ==> mac_size = 16
static uint8_t mac_size = 4;

// sizeof(output) >= sizeof(plaintext_data) + mac_size
static uint8_t output[20];

static struct AES_CCM_CONTEXT_T cxt;

volatile static uint8_t aes_done = 0;

static void aes_ecb_callback(void *dev, uint32_t len)
{
    LOG_INFO(TRACE_MODULE_APP, "AES ECB done, len = %d\r\n", len);

    for (uint32_t i = 0; i < len; i++)
    {
        if (ecb_cipher[i] != ecb_output[i])
        {
            LOG_INFO(TRACE_MODULE_APP, "AES ECB result does not match\r\n");
            break;
        }
    }

    aes_done = 1;
}

static void aes_cbc_callback(void *dev, uint32_t len)
{
    LOG_INFO(TRACE_MODULE_APP, "AES CBC done, len = %d\r\n", len);
    for (uint32_t i = 0; i < len; i++)
    {
        if (cbc_cipher[i] != cbc_output[i])
        {
            LOG_INFO(TRACE_MODULE_APP, "AES CBC result does not match\r\n");
            break;
        }
    }

    aes_done = 1;
}

static void aes_ctr_callback(void *dev, uint32_t len)
{
    LOG_INFO(TRACE_MODULE_APP, "AES CTR done, len = %d\r\n", len);
    for (uint32_t i = 0; i < len; i++)
    {
        if (ctr_cipher[i] != ctr_output[i])
        {
            LOG_INFO(TRACE_MODULE_APP, "AES CTR result does not match\r\n");
            break;
        }
    }

    aes_done = 1;
}

static void aes_ccm_encypt_callback(void *dev, uint32_t len)
{
    LOG_INFO(TRACE_MODULE_APP, "AES CCM ENCYPT done, Cipher Data len = %d,", len - mac_size);
    LOG_INFO(TRACE_MODULE_APP | TRACE_NO_OPTION, "Tag-Data len = %d\r\n", mac_size);
    for (uint32_t i = 0; i < len; i++)
    {
        if (cipher_data[i] != output[i])
        {
            LOG_INFO(TRACE_MODULE_APP, "AES CCM result does not match\r\n");
            break;
        }
    }

    aes_done = 1;
}

static void aes_ccm_decrypt_callback(void *dev, uint32_t len)
{
    for (uint32_t i = 0; i < len; i++)
    {
        if (plaintext_data[i] != output[i])
        {
            LOG_INFO(TRACE_MODULE_APP, "AES CCM DECRYPT result does not match\r\n");
            break;
        }
    }

    if (AES_MIN_VALID == aes_ccm_dec_mic_isvalid(AES_ID0))
    {
        LOG_INFO(TRACE_MODULE_APP, "AES CCM DECRYPT done, Plaintext Data len = %d\r\n", len);
        LOG_INFO(TRACE_MODULE_APP, "MACTag verification is valid\r\n");
    }
    else
    {
        LOG_INFO(TRACE_MODULE_APP, "MACTag verification is invalid\r\n");
    }

    aes_done = 1;
}

static struct AES_CFG_T usr_aes_cfg = {
    .key = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32},
    .int_en = false,
    .dma_en = true,
    .din_burst_size = 1,
    .dout_burst_size = 1,
};

int main(void)
{
    board_clock_run();
    board_pins_config();
    board_debug_console_open(TRACE_PORT_UART0);
    // Reset reason
    reset_cause_get();
    reset_cause_clear();

    // Chip calibration
    calib_chip();

    // Disable watchdog timer
    wdt_close(WDT_ID0);
    LOG_INFO(TRACE_MODULE_APP, "AES example\r\n");

    gpio_open();
    board_configure();

    aes_open(AES_ID0, &usr_aes_cfg);

    aes_done = 0;
    aes_crypt_ecb(AES_ID0, AES_DIR_ENCRYPT, ecb_input, ecb_output, 16, aes_ecb_callback);
    while (aes_done == 0)
    {
    }
    aes_done = 0;
    aes_crypt_cbc(AES_ID0, AES_DIR_ENCRYPT, cbc_iv, cbc_input, cbc_output, 16, aes_cbc_callback);
    while (aes_done == 0)
    {
    }

    aes_done = 0;
    aes_crypt_ctr(AES_ID0, ctr_initial_counter, ctr_input, ctr_output, 16, aes_ctr_callback);
    while (aes_done == 0)
    {
    }

    uint8_t tmp_key[16] = {0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf};
    aes_update_key(AES_ID0, tmp_key);
    aes_done = 0;
    cxt.adata = auth_data;
    cxt.adata_len = sizeof(auth_data);
    cxt.data_in = plaintext_data;
    cxt.data_in_len = sizeof(plaintext_data);
    cxt.nonce = nonce;
    // CCM nonce size [7 ... 13]
    cxt.nonce_size = sizeof(nonce);
    cxt.input_buf = AuthData;
    // input_buf_size >= adata_len + data_in_len + 18
    cxt.input_buf_size = sizeof(AuthData);
    cxt.output_buf = output;
    // Encrypt mode: output_buf_size >= data_in_len + mac_size
    // Decrypt mode: output_buf_size >= data_in_len - mac_size
    cxt.output_buf_size = sizeof(output);

    // CCM mac size   [4, 6, 8, 10, 12, 14, 16]
    // CCM* mac size   [0, 4, 8, 16]
    cxt.mac_size = mac_size;
    aes_crypt_ccm(AES_ID0, AES_CCM_STAR_ENCRYPT_AND_AUTH, &cxt, aes_ccm_encypt_callback);
    while (aes_done == 0)
    {
    }

    aes_done = 0;
    cxt.adata = auth_data;
    cxt.adata_len = sizeof(auth_data);
    cxt.data_in = cipher_data;
    cxt.data_in_len = sizeof(cipher_data);
    cxt.nonce = nonce;
    cxt.nonce_size = sizeof(nonce);
    cxt.input_buf = AuthData;
    cxt.input_buf_size = sizeof(AuthData);
    cxt.output_buf = output;
    cxt.output_buf_size = sizeof(output);
    cxt.mac_size = mac_size;
    aes_crypt_ccm(AES_ID0, AES_CCM_STAR_DECRYPT_AND_AUTH, &cxt, aes_ccm_decrypt_callback);
    while (aes_done == 0)
    {
    }

    LOG_INFO(TRACE_MODULE_APP, "End of AES example\r\n");

    while (1)
    {
    }
}