C#SHA256散列与Python结果不同 [英] C# SHA256 Hashing Different To Python Result

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

问题描述

我正在根据发现的Python代码编写一个小程序。我需要帮助的几行内容。



python代码如下:

  first = hashlib.sha256((valueOne + valueTwo).encode())。hexdigest()
second = hashlib.sha256(str(timestamp)+ value).encode())。hexdigest ()

当我执行它时,我的值如下:

 第一个:93046e57a3c183186e9e24ebfda7ca04e7eb4d8119060a8a39b48014d4c5172b 
第二个:bde1c946749f6716fde713d46363d90846a841ad56a4cf7eaccbb33aa b $ b

我的C#代码为:

  string first = sha256_hash((secret + auth_token)); 
string second = sha256_hash((timestamp.ToString()+ secret));

当我执行它时,我的值是:

 第一个:9346e57a3c183186e9e24ebfda7ca4e7eb4d81196a8a39b48014d4c5172b 
第二个:bde1c946749f6716fde713d46363d9846a841ad56a4cf7eaccbb33aa $ eb $ b $ c $ p $ c $ p $ c $ p $ c $ p $ c $ p $ c $ p p>如您所见,这些值略有不同。 python代码返回两个值,两个值的长度均为64个字符,其中与C#中的值分别为60个字符和63个字符。



我的sha256_hash方法来自此处: 获取字符串的SHA-256字符串



谢谢您的帮助。

解决方案

您的十六进制摘要方法不会产生length-2字节的十六进制值< 16.字节 \x08 被添加到十六进制输出中,只是'8'而不是 '08',导致输出太短。



调整格式以产生0填充的十六进制字符:

  foreach(结果字节b)
Sb.Append(b.ToString( x2));

请参见标准数字格式字符串,以获取有关如何将字节格式化为十六进制字符串的更多信息。


I'm writing a little program based off of a Python code that I have found. There is a few lines I need help with. It is about hasing a value using SHA256 encryption.

The python code is as follows:

first = hashlib.sha256((valueOne + valueTwo).encode()).hexdigest()
second = hashlib.sha256(str(timestamp) + value).encode()).hexdigest()

And when I execute it, my values are as follows:

first: 93046e57a3c183186e9e24ebfda7ca04e7eb4d8119060a8a39b48014d4c5172b
second: bde1c946749f6716fde713d46363d90846a841ad56a4cf7eaccbb33aa1eb1b70

My C# code is:

string first = sha256_hash((secret + auth_token));
string second = sha256_hash((timestamp.ToString() + secret));

And when I execute it, my values are:

first: 9346e57a3c183186e9e24ebfda7ca4e7eb4d81196a8a39b48014d4c5172b   
second: bde1c946749f6716fde713d46363d9846a841ad56a4cf7eaccbb33aa1eb1b70

As you can see, the values are slightly different. The python code returns two values BOTH with the length of 64 characters, where as in C# the values are 60 characters and 63 characters respectively.

My sha256_hash method is from here: Obtain SHA-256 string of a string

Any help would be appreciated, thanks.

解决方案

Your hex digest method is not producing length-2 hex values for bytes < 16. The byte \x08 is being added to your hex output as just '8' instead of '08', leading to an output that is too short.

Adjust the format to produce 0-padded hex characters:

foreach (Byte b in result)
    Sb.Append(b.ToString("x2"));

See Standard Numeric Format Strings for more information on how to format bytes to hexadecimal strings.

这篇关于C#SHA256散列与Python结果不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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