/* 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};

volatile uint32_t g_rsa_verify_magic = 0x52534130U; /* RSA0: not finished */
volatile int32_t g_rsa_verify_ret = 0;
volatile uint32_t g_rsa_verify_stage = 0;

static const uint8_t signature_data[512] =
{
0x13,0x70,0x3c,0xc9,0x15,0x70,0x79,0x74,0xde,0xb2,0x2f,0xd1,0x08,0x7b,0xa3,0xbf,
0x5c,0xb0,0xb6,0x32,0x26,0xe7,0x0b,0xaa,0xa2,0xe5,0x93,0x03,0xb5,0xf0,0xcf,0xb1,
0xd1,0xbf,0x9e,0x3a,0xf1,0xcf,0xce,0x7d,0x72,0x41,0x7e,0x2a,0x3f,0xce,0x26,0x01,
0x42,0x78,0xb3,0x9a,0x33,0x09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7d,0x4a,0xf6,0xd9,0xdc,0xec,0x07,0xe7,0x39,0xfd,0xde,0x2a,0x27,0xbb,0x7f,0xb8
};

/* The message that need to be signed*/
uint8_t message[32] = {};
uint8_t hashResult[32] = {0xe0,0xbc,0x61,0x4e,0x4f,0xd0,0x35,0xa4,
                          0x88,0x61,0x97,0x99,0x85,0x3b,0x07,0x51,
                          0x43,0xde,0xea,0x59,0x6c,0x47,0x7b,0x8d,
                          0xc0,0x77,0xe3,0x09,0xc0,0xfe,0x42,0xe9};
uint8_t RSA_public_key_4096_der[550] = 
{
    // SubjectPublicKeyInfo 头部（24字节）：标识为 RSA 算法
    0x30, 0x82, 0x02, 0x22, 0x30, 0x0d, 0x06, 0x09,
    0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
    0x01, 0x05, 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00,
    // PKCS#1 RSA 公钥数据（526字节）
    0x30, 0x82, 0x02, 0x0A, 0x02, 0x82, 0x02, 0x01, 0x00, 0xD3, 0xEF, 0x8F, 0x1F, 0xFA, 0x2C, 0x80,
    0x74, 0xC8, 0x7E, 0xCB, 0xEF, 0x06, 0x19, 0xB2, 0x08, 0x75, 0xF8, 0xA4, 0xD7, 0x47, 0x7A, 0x97,
    0x19, 0xAC, 0xEE, 0x6D, 0xCB, 0x5D, 0x91, 0x67, 0xBF, 0x67, 0x0B, 0xC3, 0xE6, 0x61, 0xFA, 0x00,
    0x8B, 0x07, 0x5A, 0xDD, 0x6A, 0x98, 0x9A, 0xBF, 0xB7, 0xA7, 0x6D, 0xDD, 0xC0, 0xF6, 0x16, 0x2A,
    0x00, 0xBD, 0x36, 0xE7, 0x67, 0x18, 0x98, 0x7E, 0xB3, 0x75, 0x37, 0xE9, 0xFC, 0x13, 0x1F, 0x25,
    0x67, 0xE0, 0x1F, 0xBB, 0x29, 0x4F, 0x44, 0xF1, 0x86, 0x40, 0xC3, 0xD9, 0x16, 0x20, 0xB6, 0x68,
    0x31, 0x8E, 0x40, 0xAA, 0xAC, 0x27, 0x02, 0xDC, 0x63, 0x81, 0xC4, 0x2E, 0x2E, 0xDF, 0x88, 0x18,
    0xEE, 0x80, 0x06, 0x52, 0xFD, 0x95, 0x55, 0x23, 0xAD, 0x72, 0x25, 0xD5, 0x68, 0xAD, 0xA6, 0x1A,
    0x1F, 0xBF, 0xD1, 0xBE, 0x5D, 0x51, 0xBD, 0xB2, 0x4A, 0xB7, 0xD4, 0x86, 0x35, 0x6C, 0x23, 0xE4,
    0x04, 0x7B, 0xA9, 0x6E, 0x02, 0x58, 0x55, 0x35, 0xF8, 0x55, 0x5A, 0xBE, 0x6D, 0x79, 0x7F, 0x9A,
    0xA5, 0xCA, 0x86, 0x6B, 0xCA, 0xF7, 0x98, 0x04, 0x28, 0x92, 0x72, 0xFA, 0xDD, 0x6F, 0xA8, 0x32,
    0x75, 0xB8, 0xFC, 0x0A, 0x37, 0x59, 0xF7, 0x87, 0x7E, 0x65, 0x64, 0x77, 0x16, 0x67, 0xA2, 0x95,
    0x99, 0x53, 0xD9, 0xDB, 0x1B, 0x4B, 0x74, 0x4B, 0x20, 0xC9, 0x2A, 0x7F, 0xFE, 0x4F, 0xC8, 0x37,
    0x43, 0x62, 0xF8, 0x12, 0xE8, 0x63, 0x8D, 0xB5, 0xC0, 0x53, 0x3C, 0xBD, 0xDF, 0xCA, 0xC4, 0x51,
    0x85, 0x95, 0xF3, 0x9A, 0x77, 0x74, 0xBA, 0x24, 0x49, 0x02, 0x47, 0x3E, 0xA8, 0xD0, 0x80, 0xA3,
    0xB5, 0xB6, 0x52, 0x5E, 0x6A, 0xC1, 0xA3, 0x67, 0xF2, 0x27, 0xF9, 0xF2, 0x1E, 0x0C, 0x76, 0xF3,
    0x18, 0x06, 0xCE, 0x40, 0x53, 0x94, 0x51, 0xD8, 0x34, 0x8F, 0x1D, 0xE7, 0x97, 0x48, 0x75, 0xA2,
    0xDC, 0x55, 0x8A, 0x3F, 0xE0, 0x51, 0xAA, 0x93, 0xBB, 0x57, 0x1C, 0x85, 0x5B, 0x91, 0x4E, 0xFC,
    0x4B, 0xC3, 0xCB, 0x62, 0x0B, 0xFD, 0x3C, 0xF2, 0x0D, 0xB6, 0xD4, 0xE9, 0xC1, 0xA0, 0xA4, 0xFB,
    0x72, 0xB2, 0x09, 0xF7, 0xB5, 0xF0, 0xE0, 0x44, 0x70, 0xBD, 0xDD, 0x5B, 0x52, 0x06, 0x15, 0x76,
    0xBF, 0x7B, 0x87, 0xD4, 0x50, 0x02, 0x41, 0x1D, 0x9F, 0x66, 0x80, 0xE2, 0x8F, 0x5E, 0x7D, 0x10,
    0xD0, 0x27, 0x2D, 0xF4, 0x0F, 0x22, 0x85, 0xC1, 0xE7, 0xC6, 0xD7, 0x80, 0x56, 0x63, 0xEA, 0x73,
    0x5F, 0x20, 0xE8, 0x0E, 0xE0, 0xDB, 0xAA, 0x05, 0x0F, 0x24, 0xFA, 0x6F, 0x44, 0x07, 0x7A, 0xC7,
    0x27, 0x77, 0x50, 0x83, 0x23, 0xE6, 0x81, 0xEF, 0xFC, 0x69, 0x18, 0x5C, 0xA2, 0x46, 0x05, 0xD1,
    0xFD, 0xA1, 0xA0, 0xCB, 0xED, 0x9E, 0x8D, 0x57, 0x35, 0x85, 0xC2, 0x2B, 0x0E, 0x71, 0x63, 0xE6,
    0xFE, 0x59, 0x0E, 0x50, 0x9C, 0xA2, 0xFA, 0xD9, 0x69, 0xA5, 0xE3, 0xFD, 0xAD, 0x89, 0x2A, 0x3F,
    0x8B, 0x05, 0x99, 0x5D, 0xC0, 0x33, 0x06, 0x8E, 0x69, 0x56, 0x3D, 0x9D, 0x45, 0xD5, 0x7B, 0x34,
    0x57, 0x6C, 0xE7, 0xCB, 0x81, 0xF6, 0x61, 0xF1, 0x68, 0xD2, 0xC6, 0xFF, 0xDA, 0xA3, 0x8D, 0x54,
    0x91, 0xE4, 0x79, 0x26, 0x73, 0x73, 0xE6, 0x2F, 0xB9, 0x2B, 0x63, 0x38, 0x9F, 0x45, 0xF2, 0x7E,
    0x6F, 0x3D, 0x75, 0x40, 0xA8, 0xE8, 0x5A, 0x59, 0x8E, 0x67, 0x72, 0xD5, 0x3B, 0xB5, 0x42, 0xB5,
    0xF7, 0xFF, 0x20, 0x41, 0x5C, 0x18, 0x43, 0x02, 0xA7, 0xC7, 0xFB, 0x09, 0x82, 0xA7, 0x4B, 0x92,
    0x17, 0x47, 0xE6, 0x9A, 0xD4, 0xEF, 0x44, 0x26, 0xE0, 0x8D, 0xB6, 0x94, 0x06, 0x76, 0x30, 0xCE,
    0x0B, 0x21, 0x6D, 0x52, 0x66, 0xC3, 0x7B, 0x82, 0x0D, 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的配置并填充明文数据
    g_rsa_verify_magic = 0x52534131U; /* RSA1: running */
    g_rsa_verify_stage = 1;
    g_rsa_verify_ret = 0;
    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");
        g_rsa_verify_stage = 2;
        g_rsa_verify_ret = parse_ret;
        g_rsa_verify_magic = 0x52534145U; /* RSAE: error */
        status = parse_ret;
        mbedtls_pk_free(&pk_ctx); 
        return status;
    }

    RSA_Context = mbedtls_pk_rsa(pk_ctx);

    // 4. 设置填充方式和哈希算法
    PRINTF("Setting RSA padding...\n\r");
    parse_ret = mbedtls_rsa_set_padding(RSA_Context, 
                                        MBEDTLS_RSA_PKCS_V15, 
                                        MBEDTLS_MD_SHA256);
    if(parse_ret != 0)
    {
        PRINTF("设置 RSA 填充方式失败\n");
        g_rsa_verify_stage = 3;
        g_rsa_verify_ret = parse_ret;
        g_rsa_verify_magic = 0x52534145U; /* RSAE: error */
        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");
    parse_ret = mbedtls_rsa_complete(RSA_Context);
    if(parse_ret != 0)
    {
        PRINTF("完成 RSA 公钥结构失败\n");
        g_rsa_verify_stage = 3;
        g_rsa_verify_ret = parse_ret;
        g_rsa_verify_magic = 0x52534145U; /* RSAE: error */
        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)
    {
        g_rsa_verify_stage = 4;
        g_rsa_verify_ret = parse_ret;
        g_rsa_verify_magic = 0x5253414EU; /* RSAN: verify failed */
        PRINTF("RSA no\n");
    }
    else
    {
        g_rsa_verify_stage = 5;
        g_rsa_verify_ret = 0;
        g_rsa_verify_magic = 0x5253414FU; /* RSAO: verify ok */
        PRINTF("RSA ok!\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 */

