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

时间:2018-11-18 13:15:41

标签: c# c++ sha256 hmac rsa-sha256

我正在将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] = '\0';

        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转换,但是在此之前已经有所不同。

1 个答案:

答案 0 :(得分:0)

为什么不使用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);
}