c# Base64编码解码错误结果

c# Base64 Encoding Decoding wrong result

我需要在 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();
 }

您假设您的密钥最初是使用 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 后的哈希值。这样你就可以签署任何数据,而不仅仅是字符串。