AI生成的C++hmac_sha256签名函数

发布时间 2024-01-08 19:40:47作者: -见
#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <string>
#include <iostream>

// Function to convert binary data to hexadecimal
std::string to_hex(unsigned char *data, size_t size) {
    std::string hex;
    for (size_t i = 0; i < size; ++i) {
        char buf[3];
        sprintf(buf, "%02x", data[i]);
        hex += buf;
    }
    return hex;
}

// Function to calculate HMAC-SHA256
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);
    return to_hex(hash, len);
}

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