欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用OpenSSL_EVP接口完成SHA3和国密SM3散列生成

程序员文章站 2024-03-22 17:42:34
...
    unsigned char data[128] = "测试EVP SHA3 国密SM3";
    int data_size = strlen((char*)data);

    //初始化EVP上下文
    auto ctx = EVP_MD_CTX_new();
    /*
    const EVP_MD *EVP_md5(void);
    const EVP_MD *EVP_sha1(void);
const EVP_MD *EVP_sha224(void);
const EVP_MD *EVP_sha256(void);
const EVP_MD *EVP_sha384(void);
const EVP_MD *EVP_sha512(void);
const EVP_MD *EVP_sha512_224(void);
const EVP_MD *EVP_sha512_256(void);
const EVP_MD *EVP_sha3_224(void);
const EVP_MD *EVP_sha3_256(void);
const EVP_MD *EVP_sha3_384(void);
const EVP_MD *EVP_sha3_512(void);
const EVP_MD *EVP_shake128(void);
const EVP_MD *EVP_shake256(void);
const EVP_MD *EVP_sm3(void); //1.1.1 版本开始支持
    */
    auto evp_md = EVP_sha3_512();

    //hash初始化
    EVP_DigestInit_ex(ctx, evp_md, NULL);

    //计算hash值
    EVP_DigestUpdate(ctx, data, data_size);


    //获取结果
    unsigned char out[64] = { 0 };
    unsigned int out_size = 0;
    EVP_DigestFinal_ex(ctx, out, &out_size);

    cout << "SHA3-512:";
    cout << "(" << out_size << ")";
    PrintHex(string(out, out + out_size));

    //清理上下文
    EVP_MD_CTX_free(ctx);

    //掉用EVP简化接口编码 国密SM3
    EVP_Digest(data, data_size, out, &out_size, EVP_sm3(), NULL);

    cout << "国密SM3:";
    cout << "(" << out_size << ")";
    PrintHex(string(out, out + out_size));
相关标签: 密码学