C# vs Java HmacSHA1 and then base64 [closed]

风流意气都作罢 提交于 2019-12-05 09:15:49

Try this:

// This method will return the base 64 encoded string using the given input and key.
private string EncodeHMAC(string input, byte[] key)
{
    HMACSHA1 hmac = new HMACSHA1(key);
    byte[] stringBytes = Encoding.UTF8.GetBytes(input);
    byte[] hashedValue = hmac.ComputeHash(stringBytes);
    return Convert.ToBase64String(hashedValue);
}

I don't think you're converting the hashed value to a base 64 string correctly.

I use this function to implement authentication of REST web service calls. It's important that sender and receiver use the same encoding.

Unfortunately it took me a while to find a matching PHP HAMACimplementation to this C# version.

private bool ValidateHash(String uid, String hash, DataToSign data) {
        StringBuilder strToSign = new StringBuilder();

        strToSign.Append(data.HttpMethod + '\n');
        strToSign.Append(data.Date.ToString("r") + '\n');
        strToSign.Append(data.Uri);

        Byte[] secretBytes = UTF8Encoding.UTF8.GetBytes(this._secretKey);
        HMACSHA1 hmac = new HMACSHA1(secretBytes);

        Byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(strToSign.ToString());
        Byte[] calcHash = hmac.ComputeHash(dataBytes);
        String calcHashString = Convert.ToBase64String(calcHash);

        if (calcHashString.Equals(hash)) {
            if (log.IsDebugEnabled) log.Debug(uid + " - [ValidateHash] HMAC is valid.");
            return true;
        }
        return false;
    }

Hope that helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!