与 .NET 相比,OpenSSL HMACSHA256 产生不同的结果

OpenSSL HMACSHA256 produces different result comparing to .NET

我正在使用 C#C++OpenSSL 来计算 HMACSHA256 有一个键,两者都会产生不同的结果。我做错了什么?

C#代码:

public static string CreateSignature(string signingString, string sharedKey)
{
    var key = Encoding.ASCII.GetBytes(sharedKey);
    var hmac = new HMACSHA256(key);
    var data = Encoding.ASCII.GetBytes(signingString);
    var hash = hmac.ComputeHash(data);

    return Convert.ToBase64String(hash);
}

C++代码:

std::string SignatureProvider::getSignature(std::string stringToSign, std::string key)
{
    const char* pKey = key.c_str();
    const char* pData = stringToSign.c_str();
    unsigned char* result = nullptr;
    unsigned int len = 32;

    result = (unsigned char*)malloc(sizeof(char) * len);

    HMAC_CTX ctx;
    HMAC_CTX_init(&ctx);
    HMAC_Init_ex(&ctx, pKey, strlen(pKey), EVP_sha256(), NULL);

    HMAC_Update(&ctx, (unsigned char*)&pData, strlen(pData));
    HMAC_Final(&ctx, result, &len);
    HMAC_CTX_cleanup(&ctx);

    return base64_encode(result, len);
}

std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) 
{
    std::string ret;
    int i = 0;
    int j = 0;
    unsigned char char_array_3[3];
    unsigned char char_array_4[4];

    while (in_len--) {
        char_array_3[i++] = *(bytes_to_encode++);
        if (i == 3) {
            char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
            char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
            char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
            char_array_4[3] = char_array_3[2] & 0x3f;

            for (i = 0; (i <4); i++)
                ret += base64_chars[char_array_4[i]];
            i = 0;
        }
    }

    if (i)
    {
        for (j = i; j < 3; j++)
            char_array_3[j] = '[=11=]';

        char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);

        for (j = 0; (j < i + 1); j++)
            ret += base64_chars[char_array_4[j]];

        while ((i++ < 3))
            ret += '=';
    }
    return ret;
}

为了完整起见,我只是包含了 base64 转换,但它之前已经不同了。

你为什么不用HMAC函数本身?我试过这段代码,C++ 和 C# 代码都产生了相同的 HMAC :

std::string getSignature(std::string stringToSign, std::string key)
{
    const char* pKey = key.c_str();
    const char* pData = stringToSign.c_str();
    unsigned char* result = nullptr;
    unsigned int len = 32;

    result = (unsigned char*)malloc(sizeof(char) * len);
    int nkeyLen = strlen(pKey);
    int dataLen = strlen(pData);

    result = HMAC(EVP_sha256(), pKey, nkeyLen, (unsigned char*)pData, dataLen, NULL, NULL);

    return base64_encode(result, len);
}