#include "SHA256_hash.h"

uint8_t swshaResult[32] = {0};     // SHA-256结果缓冲区(32字节=8个uint32_t)


/**
 * @brief 从Flash读取数据并使用mbedtls库中的软件SHA-256计算哈希值
 * 
 * 从Flash 0地址开始，每次读取8K数据，共读取512K数据(64次)
 */
void StepReadFlash_And_SoftWare_CalculateSHA(void)
{
    mbedtls_sha256_context Mbedtls_Context;
    uint8_t* flashAddr = (uint8_t*)HASH_FLASH_STARTADDRESS;     // PFlash1起始地址
    uint32_t chunkSize = ONECE_READ_FLASH_SIZE;                  // 每次读取8K (8192字节)
    uint32_t totalSize = READ_SECTOR_NUM;                // 总共读取128K (131072字节)
    
    // 分步计算SHA-256
    uint32_t bytesRead = 0;

    // 初始化SHA-256上下文
    mbedtls_sha256_init(&Mbedtls_Context);

    //start，需用到sha56，第二个参数填0
    mbedtls_sha256_starts(&Mbedtls_Context, 0); 

    //计算最后一块数据之前所有数据块的hash
    while (bytesRead + chunkSize < totalSize) {
        uint8_t* currentAddr = flashAddr + bytesRead;        
        mbedtls_sha256_update(&Mbedtls_Context,currentAddr,chunkSize);     
        bytesRead += chunkSize;
    }
    // 只剩最后一块数据需要计算
    uint8_t *lastAddr = flashAddr + bytesRead;
    uint32_t lastChunkSize = totalSize - bytesRead;
    mbedtls_sha256_update(&Mbedtls_Context,lastAddr,lastChunkSize);

    //结束软件sha256 hash运算
    mbedtls_sha256_finish(&Mbedtls_Context, swshaResult);

    //释放软件sha256 context
    mbedtls_sha256_free(&Mbedtls_Context);
}

void Message_And_SoftWare_CalculateSHA(uint8_t* message, size_t message_len, uint8_t* shaResult)
{
    mbedtls_sha256_context Mbedtls_Context;

    //初始化SHA-256上下文
    mbedtls_sha256_init(&Mbedtls_Context);

    //start，需用到sha56，第二个参数填0
    mbedtls_sha256_starts(&Mbedtls_Context, 0);

    //计算最后一块数据之前所有数据块的hash
    mbedtls_sha256_update(&Mbedtls_Context,
                            message,
                            message_len);

    //结束软件sha256 hash运算
    mbedtls_sha256_finish(&Mbedtls_Context, shaResult);

    //释放软件sha256 context
    mbedtls_sha256_free(&Mbedtls_Context);
}