在C中无法获得与python中相同的哈希

2024-09-27 21:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串,我需要哈希以访问API。API creator在Python中提供了一个代码片段,它将代码散列如下:

hashed_string = hashlib.sha1(string_to_hash).hexdigest()

使用这个哈希字符串访问API时,一切正常。我试图在C#中获得相同的哈希字符串结果,但没有成功。我试过很多方法,但到目前为止都没用。我也知道hexdigest的部分,当我试图模仿行为时,我一直牢记这一点。在

有人知道如何在C中得到同样的结果吗?在

编辑: 这是我试图在C#中复制相同结果的许多方法之一:

^{pr2}$

此代码取自:Hashing with SHA1 Algorithm in C#

另一种方法

public string ToHexString(string myString)
{
    HMACSHA1 hmSha1 = new HMACSHA1();
    Byte[] hashMe = new ASCIIEncoding().GetBytes(myString);
    Byte[] hmBytes = hmSha1.ComputeHash(hashMe);
    StringBuilder hex = new StringBuilder(hmBytes.Length * 2);
    foreach (byte b in hmBytes)
    {
        hex.appendFormat("{0:x2}", b);
    }
    return hex.ToString();
}

此代码取自:Python hmac and C# hmac

编辑2

一些输入/输出:

C#(使用上述描述中提供的第二种方法)

输入:callerId1495610997apiKey3*&E#N@B1层)O) -1年

输出:1ecd2b66e152f0965adb96727d96b8f5db588a


Python

输入:callerId1495610997apiKey3*&E#N@B1层)O) -1年

输出:bf11a12bbac84737a39152048e299fa54710d24e


C#(使用上述描述中提供的第一种方法)

输入:callerId1495611935 apiKey{[B{+%p)s;WD5&5x

输出:7e81e0d40ff83faf1173394930443654a2b39cb3


Python

输入:callerId1495611935 apiKey{[B{+%p)s;WD5&5x

输出:512158bbdbc78b1f25f67e963fefdc8b6cbcd741


Tags: 方法字符串代码inapi编辑newstring
1条回答
网友
1楼 · 发布于 2024-09-27 21:28:35

C:

public static string Hash(string input)
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(input));
        var sb = new StringBuilder(hash.Length * 2);

        foreach (byte b in hash)
        {
            sb.Append(b.ToString("x2")); // x2 is lowercase
        }

        return sb.ToString().ToLower();
    }
}

public static void Main()
{
    var x  ="callerId1495611935​apiKey{[B{+%P)s;WD5&5x";
    Console.WriteLine(Hash(x)); // prints 7e81e0d40ff83faf1173394930443654a2b39cb3
}

Python

^{pr2}$

您的主要问题是在C和Python中对同一个字符串使用不同的编码。在两种语言中使用UTF8并使用相同的大小写。输出是一样的。在

注意在输入字符串(介于callerId1495611935apiKey{[B{+%P)s;WD5&5x)内有一个隐藏的^{} character。这就是为什么用UTF-8编码字符串与使用ASCII编码结果不同的原因。这个字符必须在你的字符串中吗?在

相关问题 更多 >

    热门问题