Python hmac和C#hmac [英] Python hmac and C# hmac

查看:89
本文介绍了Python hmac和C#hmac的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个python网络服务.它需要一个哈希作为参数.python中的哈希是通过这种方式生成的.

We have a python web service. It needs a hash as a parameter. The hash in python is generated this way.

    hashed_data = hmac.new("ant", "bat", hashlib.sha1)
    print hashed_data.hexdigest()

现在,这就是我从C#生成哈希的方法.

Now, this is how I generate the hash from C#.

    ASCIIEncoding encoder = new ASCIIEncoding();
    Byte[] code = encoder.GetBytes("ant");
    HMACSHA1 hmSha1 = new HMACSHA1(code);
    Byte[] hashMe = encoder.GetBytes("bat");
    Byte[] hmBytes = hmSha1.ComputeHash(hashMe);
    Console.WriteLine(Convert.ToBase64String(hmBytes));

但是,我得出的结果是不同的.

However, I'm coming out with different result.

我应该更改哈希的顺序吗?

Should I change the order of the hashing?

谢谢

乔恩

推荐答案

为了打印结果:

  • 在Python中,您使用: .hexdigest()
  • 在C#中,您使用: Convert.ToBase64String

那两个函数根本不做相同的事情.Python的十六进制摘要将字节数组简单地转换为十六进制字符串,而C#方法使用Base64编码来转换字节数组.因此,要获得相同的输出,只需定义一个函数:

Those 2 functions don't do the same thing at all. Python's hexdigest simply converts the byte array to a hex string whereas the C# method uses Base64 encoding to convert the byte array. So to get the same output simply define a function:

public static string ToHexString(byte[] array)
{
    StringBuilder hex = new StringBuilder(array.Length * 2);
    foreach (byte b in array)
    {
        hex.AppendFormat("{0:x2}", b);
    }
    return hex.ToString();
}

然后:

ASCIIEncoding encoder = new ASCIIEncoding();
Byte[] code = encoder.GetBytes("ant");
HMACSHA1 hmSha1 = new HMACSHA1(code);
Byte[] hashMe = encoder.GetBytes("bat");
Byte[] hmBytes = hmSha1.ComputeHash(hashMe);
Console.WriteLine(ToHexString(hmBytes));

现在,您将获得与Python中相同的输出:

Now you will get the same output as in Python:

739ebc1e3600d5be6e9fa875bd0a572d6aee9266

这篇关于Python hmac和C#hmac的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆