与相比,OpenSSL HMACSHA256会产生不同的结果.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] = '';
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);
}

相关内容

  • 没有找到相关文章