You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac平台C++使用CommonHMAC实现带密钥的SHA512加密问题

HMAC-SHA512 实现修复方案

现有代码问题

  • 你返回的result是HMAC计算输出的64字节原始二进制数据,直接用裸指针构造std::string会被识别为以\0结尾的C字符串,一旦二进制数据中出现\0就会被截断,且长度识别错误,无法得到正确结果
  • malloc分配的内存没有主动释放,会产生内存泄漏
  • 通常业务场景下需要把二进制哈希值转成十六进制字符串使用,你当前的代码缺少这一步转换逻辑

修复后可运行实现

#include <CommonCrypto/CommonHMAC.h>
#include <string>
#include <sstream>
#include <iomanip>

std::string sha512_encoder(const std::string& secret, const std::string& data){
    // 初始化存储二进制结果的缓冲区,SHA512输出固定为CC_SHA512_DIGEST_LENGTH即64字节
    unsigned char result[CC_SHA512_DIGEST_LENGTH];
    
    // 调用CCHmac原生接口计算HMAC-SHA512
    CCHmac(kCCHmacAlgSHA512, 
           secret.c_str(), 
           secret.size(), 
           data.c_str(), 
           data.size(), 
           result);
    
    // 将二进制结果转换为常用的小写十六进制字符串
    std::stringstream ss;
    ss << std::hex << std::setfill('0');
    for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++){
        ss << std::setw(2) << static_cast<unsigned int>(result[i]);
    }
    
    return ss.str();
}

如果你确实需要原始二进制格式的返回值,不需要转十六进制的话,可以去掉字符串转换逻辑,直接返回std::string(reinterpret_cast<char*>(result), CC_SHA512_DIGEST_LENGTH);,明确指定字符串长度即可避免二进制内容被截断。

内容的提问来源于stack exchange,提问作者Sam Moldenha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:06:04