在 C# 中重新创建 python b64encode 和 hmac 函数时出现问题

Problem with recreating python b64encode and hmac function in C#

我必须创建一个函数来生成与 python 中完全相同的签名。这是我的代码

 if __name__ == '__main__':
    client_secret = 'aasfeef422c2dsa84fe9e7f56e6f214b'
    client_key_id = 'PHFg6w5XwnIYasDvdkqSjA=='
    nonce = 'fb807056-0d41-4c55-aa65-598a600bfe49'
    timestamp = '2022-04-01T06:57:50.280Z'

    signature = b64encode(hmac.new(b64decode(client_secret), msg=bytes(client_key_id + nonce + timestamp, 'utf-8'),
                                   digestmod=hashlib.sha256).digest()).decode('utf-8')

这里签名的值为:'eenCmMzL12aPGat2zouBCaQQh9dC+8mJsm1KNpYQmOs='

我写了一个 C# 函数,代码如下所示:

        private static string Base64Encode(string text)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(text);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        private static string GetHMAC(string text, string key)
        {
            key = key ?? "";

            using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(key)))
            {
                var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
                return Convert.ToBase64String(hash);
            }
        }

        public static void Main(string[] args)
        {
            var client_secret = "aasfeef422c2dsa84fe9e7f56e6f214b";
            var client_key_id = "PHFg6w5XwnIYasDvdkqSjA==";
            var nonce = "fb807056-0d41-4c55-aa65-598a600bfe49";
            var timestamp = "2022-04-01T06:57:50.280Z";

            var hmac = GetHMAC(client_key_id + nonce + timestamp, Base64Encode(client_secret));
            var signature = Base64Encode(hmac);   
        }

不幸的是这里签名的值为"dklPYzdlOEhjS1pZaU1UdkYweWRGZTRhZkFvUEF6djhiMUxpMFZOL2x1Yz0="

这是一个巨大的差异。您知道如何解决该问题,并使 C# 算法生成与 python 算法相同的签名吗?

您的 C# 代码存在很多问题,包括对相同数据执行重复的 Base64 编码。正确代码比较简单:

private static string GetHMAC(string text, byte[] key)
{
    using (var hmacsha256 = new HMACSHA256(key))
    {
        var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(text));
        return Convert.ToBase64String(hash);
    }
}

public static void Main(string[] args)
{
    var client_secret = "aasfeef422c2dsa84fe9e7f56e6f214b";
    var client_key_id = "PHFg6w5XwnIYasDvdkqSjA==";
    var nonce = "fb807056-0d41-4c55-aa65-598a600bfe49";
    var timestamp = "2022-04-01T06:57:50.280Z";

    var hmac = GetHMAC(client_key_id + nonce + timestamp, Convert.FromBase64String(client_secret));
    Console.WriteLine(hmac);
}

这会按预期输出 eenCmMzL12aPGat2zouBCaQQh9dC+8mJsm1KNpYQmOs=