#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/err.h>
#include <string.h>
#include <stdio.h>

void handleErrors(void)
{
    ERR_print_errors_fp(stderr);
    abort();
}

void sm3_hash(const unsigned char *input, size_t input_len, unsigned char *output)
{
    EVP_MD_CTX *mdctx;
    const EVP_MD *md;
    unsigned int md_len;

    md = EVP_sm3(); // 使用 SM3 算法
    mdctx = EVP_MD_CTX_new();
    if (mdctx == NULL)
        handleErrors();

    if (1 != EVP_DigestInit_ex(mdctx, md, NULL))
        handleErrors();

    if (1 != EVP_DigestUpdate(mdctx, input, input_len))
        handleErrors();

    if (1 != EVP_DigestFinal_ex(mdctx, output, &md_len))
        handleErrors();

    EVP_MD_CTX_free(mdctx);
}

int main(void)
{
    unsigned char data[] = "Hello, SM3!";
    unsigned char hash_value[EVP_MAX_MD_SIZE];
    int i;

    printf("Original Data: %s\n", data);

    sm3_hash(data, strlen((char *)data), hash_value);

    printf("SM3 Hash Value: ");
    for (i = 0; i < EVP_MD_size(EVP_sm3()); i++)
        printf("%02x", hash_value[i]);
    printf("\n");

    return 0;
}
