c#Base64编码解码错误结果

时间:2016-10-18 06:09:24

标签: c# encoding decoding hmac

我需要在c#中创建一个哈希签名。

我需要在c#代码中实现的伪代码示例:

Signatur(Request) = new String(encodeBase64URLCompatible(HMAC-SHA-256(getBytes(Z, "UTF-8"), decodeBase64URLCompatible(getBytes(S, "UTF-8")))), "UTF-8")

Z:apiSecret S:stringToSign

expectedSignaturapiSecret的编码为Base64 URL Encoding [RFC 4648 Section 5]

我的问题是我总是得到错误的结果。

public static string Base64Decode(string base64EncodedData)
{
    var base64EncodedBytes = Convert.FromBase64String(base64EncodedData);
    return Encoding.UTF8.GetString(base64EncodedBytes);
}

public static string Base64Encode(string plainText)
{
    var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
    return Convert.ToBase64String(plainTextBytes);
}

private static byte[] HmacSha256(string data, string key)
{
     using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
     {
       return hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
     }
}

static void Main(string[] args)
{
     var apiSecret = "JrXRHCnUegQJAYSJ5J6OvEuOUOpy2q2-MHPoH_IECRY=";
     var stringToSign = "f3fea5f3-60af-496f-ac3e-dbb10924e87a:20160201094942:e81d298b-60dd-4f46-9ec9-1dbc72f5b5df:Qg5f0Q3ly1Cwh5M9zcw57jwHI_HPoKbjdHLurXGpPg0yazdC6OWPpwnYi22bnB6S";
     var expectedSignatur = "ps9MooGiTeTXIkPkUWbHG4rlF3wuTJuZ9qcMe-Y41xE=";

     apiSecret = apiSecret.Replace('-', '+').Replace('_', '/').PadRight(apiSecret.Length + (4 - apiSecret.Length % 4) % 4, '=');

     var secretBase64Decoded = Base64Decode(apiSecret);

     var hmac = Convert.ToBase64String(HmacSha256(secretBase64Decoded, stringToSign));

     var signatur = hmac.Replace('+', '-').Replace('/', '_');


     Console.WriteLine($"signatur: {signatur}");
     Console.WriteLine($"expected: {expectedSignatur}");

     Console.WriteLine(signatur.Equals(expectedSignatur));
     Console.ReadLine();
 }

1 个答案:

答案 0 :(得分:2)

您假设您的密钥最初是使用UTF-8进行文本编码的 - 但它看起来并非如此。您应该将逻辑上二进制数据保留为二进制数据 - 您根本不需要Base64EncodeBase64Decode方法。相反,您的HmacSha256方法应该使用byte[]作为密钥,您只需使用Convert.FromBase64String从base64编码的密码中获取这些字节:

using System;
using System.Text;
using System.Security.Cryptography;

class Test
{    
    private static byte[] HmacSha256(byte[] key, string data)
    {
        using (var hmac = new HMACSHA256(key))
        {
            return hmac.ComputeHash(Encoding.UTF8.GetBytes(data));
        }
    }

    static void Main(string[] args)
    {
        var apiSecret = "JrXRHCnUegQJAYSJ5J6OvEuOUOpy2q2-MHPoH_IECRY=";
        var stringToSign = "f3fea5f3-60af-496f-ac3e-dbb10924e87a:20160201094942:e81d298b-60dd-4f46-9ec9-1dbc72f5b5df:Qg5f0Q3ly1Cwh5M9zcw57jwHI_HPoKbjdHLurXGpPg0yazdC6OWPpwnYi22bnB6S";
        var expectedSignatur = "ps9MooGiTeTXIkPkUWbHG4rlF3wuTJuZ9qcMe-Y41xE=";

        apiSecret = apiSecret.Replace('-', '+').Replace('_', '/').PadRight(apiSecret.Length + (4 - apiSecret.Length % 4) % 4, '=');

        var secretBase64Decoded = Convert.FromBase64String(apiSecret);

        var hmac = Convert.ToBase64String(HmacSha256(secretBase64Decoded, stringToSign));

        var signatur = hmac.Replace('+', '-').Replace('/', '_');
        Console.WriteLine($"signatur: {signatur}");
        Console.WriteLine($"expected: {expectedSignatur}");            
        Console.WriteLine(signatur.Equals(expectedSignatur));
    }
}

我个人将您的HmacSha256方法更改为:

private static byte[] ComputeHmacSha256Hash(byte[] key, byte[] data)
{
    using (var hmac = new HMACSHA256(key))
    {
        return hmac.ComputeHash(data);
    }
}

因此它更通用,可能为了方便起见,在编码为UTF-8之后添加另一种计算哈希的方法。这样您就可以签署任何数据,而不仅仅是字符串。