chatGPT用C++写的HMAC-SHA256函数

该文章介绍了如何在C++中使用OpenSSL库的HMAC_SHA256函数计算字符串的哈希值,包括函数定义、参数和编译链接步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下内容全为 chatGPT 生成:

#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <iostream>
#include <iomanip>

std::string hmac_sha256(const std::string &key, const std::string &data) {
    unsigned char hash[SHA256_DIGEST_LENGTH];
    HMAC_CTX hmac;
    HMAC_CTX_init(&hmac);
    HMAC_Init_ex(&hmac, &key[0], key.length(), EVP_sha256(), NULL);
    HMAC_Update(&hmac, (unsigned char*)&data[0], data.length());
    unsigned int len = SHA256_DIGEST_LENGTH;
    HMAC_Final(&hmac, hash, &len);
    HMAC_CTX_cleanup(&hmac);

    std::stringstream ss;
    for(unsigned int i = 0; i < len; i++)
    {
        ss << std::hex << std::setw(2) << std::setfill('0') << (int)hash[i];
    }

    return ss.str();
}

int main() {
    std::string key = "your_key";
    std::string data = "your_data";
    std::string hash = hmac_sha256(key, data);
    std::cout << "HMAC-SHA256: " << hash << std::endl;
    return 0;
}

在这个代码片段中,hmac_sha256函数接受一个密钥和一个数据字符串,然后使用HMAC-SHA256算法计算哈希值。然后,它将哈希值转换为十六进制字符串,并返回。

注意,你需要在你的系统中安装OpenSSL库,并在编译你的程序时链接OpenSSL库。你可以使用以下命令来编译你的程序:

g++ your_program.cpp -o your_program -lcrypto

在这个命令中,your_program.cpp是你的程序的源文件,your_program是你想要生成的可执行文件的名称,-lcrypto是链接OpenSSL库的选项。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值