/* USER CODE BEGIN Header */
/* you can remove the copyright */

/*
 *  Copyright 2020-2023 Yuntu Microelectronics co.,ltd
 *  All rights reserved.
 *
 *  YUNTU Confidential. This software is owned or controlled by YUNTU and may only be
 *  used strictly in accordance with the applicable license terms. By expressly
 *  accepting such terms or by downloading, installing, activating and/or otherwise
 *  using the software, you are agreeing that you have read, and that you agree to
 *  comply with and are bound by, such license terms. If you do not agree to be
 *  bound by the applicable license terms, then you may not retain, install,
 *  activate or otherwise use the software. The production use license in
 *  Section 2.3 is expressly granted for this software.
 *
 * @file main.c
 * @brief
 *
 */

/* USER CODE END Header */
#include "sdk_project_config.h"
/* Includes ------------------------------------------------------------------*/

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "printf.h"
#include "psa/crypto.h"
#include "mbedtls/platform.h"
#include "SHA256_hash.h"
#include "rsa.h"
#include "pk.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
uint8_t hwshaResult[32] = {0};

static const uint8_t signature_data[512] =
{
    0x19, 0x27, 0x2B, 0x33, 0xD1, 0x98, 0x8D, 0xC7, 0x69, 0xA6, 0x7C, 0xEE, 0x4C, 0xCA, 0xCC, 0xF7, 0x66, 0xC4, 0xE7, 0xA5, 0x6C, 0xFA, 0x65, 0x8A, 0x38, 0x8E, 0x50, 0xCE, 0x52, 0xFE, 0x4B, 0x2B, 0x11, 0x9E, 0x19, 0x8E, 0xE7, 0xCF, 0xD7, 0x75, 0x10, 0x3A, 0xE9, 0xC3, 0xF4, 0x32, 0x25, 0xCE, 0xE5, 0x4E, 0xBB, 0x04, 0x01, 0x8C, 0xAF, 0xB2, 0x97, 0xD8, 0xE0, 0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 0x6F, 0x0A, 0xEF, 0x31, 0x7E, 0xED, 0x0D, 0xBD, 0x51, 0x6A, 0x2D, 0xCF, 0x37, 0x36, 0x5E, 0xB7, 0xE9, 0xD5, 0xDF, 0x76, 0xBA, 0xAA, 0x99, 0x21, 0xA5, 0x2E, 0x97, 0x3B, 0x82, 0x79, 0x5C, 0x56, 0xE2, 0x9B, 0x07, 0x04, 0x17, 0x75, 0x34, 0xB0, 0x44, 0x43, 0xFD, 0xAB, 0x97, 0xD1, 0x75, 0xE0, 0xB9, 0xE9, 0xA4, 0x83, 0x98, 0x8F, 0xC9, 0x73, 0x7B, 0xD0, 0x5C, 0x5D, 0xAC, 0xB7, 0xD1, 0xA2, 0x31, 0xF3, 0x77, 0x01, 0x9A, 0x02, 0xFA, 0xB0, 0x6F, 0x7E, 0xF8, 0x79, 0xD8, 0x73, 0x1A, 0x33, 0x20, 0x90, 0x67, 0xD0, 0x44, 0x35, 0xDE, 0xA4
};

/* The message that need to be signed*/
uint8_t message[32] = {};

uint8_t RSA_public_key_4096_der[550] = 
{
    0x30, 0x82, 0x02, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
    0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00,
    0x30, 0x82, 0x02, 0x0a, 0x02, 0x82, 0x02, 0x01, 0x00, 0xa7, 0x36, 0x21,
    0x07, 0xde, 0xa5, 0x40, 0x42, 0x74, 0xaf, 0xf0, 0x7d, 0xe3, 0x7a, 0x40,
    0xb9, 0x75, 0x0d, 0x1b, 0xc2, 0xe8, 0xcc, 0x42, 0xa6, 0xac, 0xc1, 0x51,
    0xc1, 0x55, 0x77, 0xb7, 0x6c, 0xab, 0xd0, 0x66, 0xc1, 0x5f, 0xa6, 0xd3,
    0x50, 0x4b, 0x38, 0x9e, 0xb1, 0xbe, 0x31, 0xfe, 0xc0, 0xc5, 0x84, 0x1d,
    0xb4, 0x4b, 0x1b, 0xd4, 0x6b, 0x68, 0xdd, 0x87, 0xc4, 0x66, 0x50, 0x1e,
    0x1c, 0x79, 0x89, 0x4c, 0x07, 0x8c, 0x65, 0x6b, 0x94, 0x15, 0xf5, 0x1e,
    0x23, 0x16, 0x19, 0xbe, 0xc7, 0x29, 0x62, 0xd8, 0xdf, 0xdc, 0x59, 0x8e,
    0xe5, 0xcb, 0xd5, 0xda, 0x97, 0x69, 0x1c, 0x40, 0x30, 0xa1, 0x27, 0xbf,
    0x89, 0xfc, 0xf7, 0x69, 0x00, 0xe1, 0x8f, 0xf4, 0xf7, 0xf5, 0x53, 0xda,
    0x48, 0x9b, 0xb7, 0xe2, 0x61, 0x32, 0xab, 0x00, 0xf3, 0x86, 0xc5, 0xdf,
    0xc1, 0xc4, 0x32, 0x88, 0x20, 0xe8, 0x90, 0x2b, 0x28, 0x86, 0x2b, 0x7a,
    0x13, 0xd8, 0x94, 0xa6, 0x73, 0x57, 0x67, 0x49, 0x70, 0xf8, 0x7b, 0x9b,
    0xbd, 0xed, 0x07, 0x78, 0x08, 0xbe, 0x32, 0x81, 0xe3, 0x6e, 0xc8, 0x7a,
    0x76, 0x60, 0x5b, 0xdf, 0x8a, 0x43, 0x11, 0xba, 0x3d, 0xc5, 0x22, 0x52,
    0x42, 0xa9, 0xd7, 0x7e, 0xae, 0x0e, 0xc6, 0xe4, 0x72, 0xc8, 0x3c, 0x33,
    0xce, 0x07, 0xd1, 0x18, 0x2b, 0x26, 0x1b, 0xb7, 0xdc, 0x64, 0xc6, 0x86,
    0x50, 0x7f, 0x16, 0x37, 0xb0, 0x01, 0x24, 0x7b, 0x0f, 0x86, 0x16, 0xae,
    0xaf, 0xe1, 0x10, 0x83, 0x14, 0xe9, 0xff, 0x62, 0xcd, 0x30, 0x1c, 0x50,
    0x92, 0x10, 0x19, 0x31, 0x5e, 0x0c, 0xca, 0x96, 0x97, 0xf6, 0xae, 0xcb,
    0xed, 0xbf, 0xbf, 0x0a, 0x6d, 0x1f, 0x5e, 0x2e, 0xfe, 0x80, 0xa1, 0x30,
    0x26, 0x30, 0x35, 0x41, 0xf8, 0x5b, 0xd6, 0x95, 0x07, 0x96, 0x5c, 0x91,
    0x23, 0x94, 0x01, 0x35, 0x6b, 0x2c, 0x0a, 0xb7, 0x03, 0xe4, 0x93, 0x53,
    0x81, 0x48, 0x40, 0x1e, 0x9d, 0x51, 0xb2, 0x8c, 0xd4, 0x47, 0x7c, 0x76,
    0xb0, 0x80, 0x7d, 0x62, 0xb5, 0xc8, 0x95, 0x78, 0xba, 0x2a, 0x0a, 0xfe,
    0xdc, 0x9f, 0x87, 0xc2, 0xcf, 0x5e, 0x4f, 0xd2, 0x07, 0xf7, 0x5a, 0x6a,
    0x32, 0x4b, 0x77, 0x2f, 0x5a, 0xc3, 0xf0, 0x61, 0x0e, 0xea, 0x20, 0xe7,
    0xe4, 0x1c, 0x5d, 0xc4, 0xba, 0xc9, 0x40, 0x4d, 0xc2, 0x7e, 0x11, 0xed,
    0x39, 0x13, 0xa5, 0xdf, 0xc0, 0xfa, 0xdd, 0x8c, 0x98, 0x2a, 0x34, 0x12,
    0x53, 0x55, 0x05, 0x64, 0x9c, 0xa0, 0x49, 0x06, 0x7e, 0xd4, 0xb2, 0xfc,
    0xa7, 0x7e, 0x3e, 0x50, 0xb1, 0x1a, 0xf7, 0x83, 0x7b, 0x2f, 0xe9, 0xde,
    0x6a, 0x24, 0x09, 0x72, 0xde, 0xdd, 0x32, 0xeb, 0xfa, 0xfc, 0x29, 0xf0,
    0x8f, 0x3f, 0x47, 0x23, 0x4b, 0x08, 0x31, 0x07, 0x92, 0xde, 0x02, 0x26,
    0xb4, 0xb0, 0xbb, 0x66, 0x7b, 0x35, 0x55, 0x68, 0x44, 0xae, 0xe3, 0x31,
    0x42, 0xa4, 0x0d, 0xa0, 0x1f, 0xce, 0x7d, 0x7f, 0xa2, 0x35, 0x08, 0xbd,
    0x42, 0x93, 0x95, 0x96, 0xea, 0xaf, 0xa4, 0x20, 0x69, 0xdb, 0xfb, 0xb0,
    0x23, 0x6a, 0xb4, 0x18, 0x75, 0xb6, 0x2a, 0x67, 0x38, 0xeb, 0x84, 0x5e,
    0x61, 0xa5, 0x43, 0x0c, 0x94, 0x8b, 0x7b, 0xa7, 0x3e, 0x3e, 0x00, 0x04,
    0x8a, 0xab, 0x46, 0x52, 0xc3, 0x3e, 0xe2, 0xba, 0x1f, 0xc6, 0x20, 0x16,
    0x87, 0x73, 0x13, 0x3c, 0xea, 0xcc, 0xcb, 0x27, 0xa5, 0x4c, 0xed, 0x4b,
    0x9a, 0x6d, 0x15, 0xd0, 0xf3, 0x3a, 0x83, 0x6f, 0xa2, 0x25, 0x43, 0x79,
    0x2e, 0x16, 0xe4, 0xdb, 0x4f, 0x98, 0x8d, 0xe0, 0x5e, 0xe9, 0x6f, 0x45,
    0xe3, 0x7f, 0xf0, 0xd1, 0xfd, 0x19, 0x3d, 0x11, 0xc4, 0xb5, 0x60, 0xc9,
    0xa8, 0x00, 0x64, 0xa4, 0xbd, 0x02, 0x03, 0x01, 0x00, 0x01,
};

/* USER CODE END PV */

/* Private function declare --------------------------------------------------*/
/* USER CODE BEGIN PFDC */
extern void mbedtls_config_init();
/* USER CODE END PFDC */
static void Board_Init(void);

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
void StepReadFlash_And_HardWare_CalculateSHA(void)
{
    uint8_t* flashAddr = (uint8_t*)0x80000;  // Flash起始地址
    uint32_t chunkSize = 8192;                  // 每次读取8K (8192字节)
    uint32_t totalSize = 524288;                // 总共读取512K (524288字节)

    // 分步计算SHA-256
    uint32_t bytesRead = 0;

    // 第一块: 使用MSG_START标志
    HCU_DRV_GenerateSHA(flashAddr, chunkSize, totalSize, HCU_SHA_256, MSG_START, NULL);
    bytesRead += chunkSize;
    
    // 中间块: 使用MSG_MIDDLE标志
    while (bytesRead + chunkSize < totalSize) {
        uint8_t* currentAddr = flashAddr + bytesRead;          
        
        HCU_DRV_GenerateSHA(currentAddr, chunkSize, 0, HCU_SHA_256, MSG_MIDDLE, NULL);
        bytesRead += chunkSize;
    }

    // 最后一块: 使用MSG_END标志并获取结果
    uint8_t *lastAddr = flashAddr + bytesRead;
    uint32_t lastChunkSize = totalSize - bytesRead;
    HCU_DRV_GenerateSHA(lastAddr, lastChunkSize, 0, HCU_SHA_256, MSG_END, hwshaResult);
}
/* USER CODE END 0 */


/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{
    /* USER CODE BEGIN 1 */
    uint8_t hashResult[32] = {0};
    psa_status_t status;
    mbedtls_pk_context pk_ctx;  // 公钥上下文（用于提取公钥）
    mbedtls_rsa_context *RSA_Context; // RSA 上下文（用于签名验证）

    /* USER CODE END 1 */ 
    Board_Init();
    /* USER CODE BEGIN 2 */

    // 1. 初始化mbedtls的配置并填充明文数据
    mbedtls_config_init();
    mbedtls_pk_init(&pk_ctx);

#if READ_FLASH_TEST_APPLICATION
    //初始化mbedtls sha56
    PINS_DRV_SetPins(GPIOE, (1 << 23));
    #if hash_calculate_MODE
        // 1. 读取Flash并使用硬件计算SHA256作为明文
        StepReadFlash_And_HardWare_CalculateSHA();
        PINS_DRV_ClearPins(GPIOE, (1 << 23));
        //将硬件计算的hash值填到本工程的message数组
        for(uint8_t i = 0; i < 32; i++){
            message[i] = hwshaResult[i];
        }

        // 2. 计算明文的hash（SHA256）值
        HCU_DRV_GenerateSHA(message, 
                            sizeof(message), 
                            sizeof(message), 
                            HCU_SHA_256, 
                            MSG_ALL, 
                            hashResult);
    #else
        PINS_DRV_SetPins(GPIOE, (1 << 23));
        // 1. 读取Flash并使用软件计算SHA256作为明文
        StepReadFlash_And_SoftWare_CalculateSHA();
        PINS_DRV_ClearPins(GPIOE, (1 << 23));
        //将软件计算的hash值填到本工程的message数组
        for(uint8_t i = 0; i < 32; i++){
            message[i] = swshaResult[i];
        }

        // 2. 计算明文的hash（SHA256）值
        Message_And_SoftWare_CalculateSHA(message, sizeof(message), hashResult);
    #endif
#endif


    // 3. 解析数据
    PRINTF("Parsing RSA DER...\n\r");
    int parse_ret = mbedtls_pk_parse_public_key(
        &pk_ctx,                  
        RSA_public_key_4096_der,      
        sizeof(RSA_public_key_4096_der)   
    );

    if (parse_ret != 0) {
        PRINTF("公钥解析失败\n");
        status = parse_ret;
        mbedtls_pk_free(&pk_ctx); 
        return status;
    }

    RSA_Context = mbedtls_pk_rsa(pk_ctx);

    // 4. 设置填充方式和哈希算法
    PRINTF("Setting RSA padding...\n\r");
    mbedtls_rsa_set_padding(RSA_Context, 
                            MBEDTLS_RSA_PKCS_V15, 
                            MBEDTLS_MD_SHA256);
    if(parse_ret != 0)
    {
        PRINTF("设置 RSA 填充方式失败\n");
        status = parse_ret;
        mbedtls_pk_free(&pk_ctx);
        mbedtls_rsa_free(RSA_Context);
        return status;
    }

    // 5. 完成 RSA 公钥结构
    PRINTF("Completing RSA public key structure...\n\r");
    mbedtls_rsa_complete(RSA_Context);
    if(parse_ret != 0)
    {
        PRINTF("完成 RSA 公钥结构失败\n");
        status = parse_ret;
        mbedtls_pk_free(&pk_ctx);
        mbedtls_rsa_free(RSA_Context);
        return status;
    }

    // 6. 验证签名
    PRINTF("Verifying RSA signature...\n\r");
    parse_ret = mbedtls_rsa_pkcs1_verify(RSA_Context,
                                        MBEDTLS_MD_SHA256,
                                        32,
                                        hashResult,
                                        signature_data);
    if(parse_ret != 0)
    {
        PRINTF("RSA 签名验证失败\n");
    }
    else
    {
        PRINTF("RSA 签名验证成功\n");
    }
    mbedtls_pk_free(&pk_ctx);
    mbedtls_rsa_free(RSA_Context);
    /* USER CODE END 2 */

    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1)
    {
        /* USER CODE END WHILE */
        /* USER CODE BEGIN 3 */
    }
    /* USER CODE END 3 */
}

static void Board_Init(void)
{
    CLOCK_SYS_Init(g_clockManConfigsArr,CLOCK_MANAGER_CONFIG_CNT,g_clockManCallbacksArr,CLOCK_MANAGER_CALLBACK_CNT);
    CLOCK_SYS_UpdateConfiguration(CLOCK_MANAGER_ACTIVE_INDEX,CLOCK_MANAGER_POLICY_AGREEMENT);
    PINS_DRV_Init(NUM_OF_CONFIGURED_PINS0,g_pin_mux_InitConfigArr0);
    UTILITY_PRINT_Init();
    HCU_DRV_Init(&hcu_config0,&hcu_config0_State);
    FLASH_DRV_Init(0,&flash_config0,&flash_config0_State);
}

/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
