如何将此 HashSHA256(("").Encode("utf-8")).HexDigest() 转换为 C#?
How can I convert this HashSHA256(("").Encode("utf-8")).HexDigest() to C#?
下一个伪代码来自AWS documentation (section: Task 1, step 7):
payload_hash = HashSHA256(("").Encode("utf-8")).HexDigest()
用于计算GET请求的负载。
为方便起见,此伪代码可以重写为以下方式:
utf8Bytes = ("").Encode("utf-8")
sha256Hash = HashSHA256(utf8Bytes)
payload_hash = sha256Hash.HexDigest()
如何将此伪代码转换为 C#
?
下一个示例 C#
相当于您提供的伪代码:
using System;
using System.Security.Cryptography;
using System.Text;
...
public static void Demo()
{
using (SHA256 sha256 = SHA256.Create())
{
string textToHash = "";
byte[] bytesToHash = Encoding.UTF8.GetBytes(textToHash);
byte[] hash = sha256.ComputeHash(bytesToHash);
string hexDigest = ToHexStr(hash);
Console.WriteLine(hexDigest);
}
}
public static string ToHexStr(byte[] hash)
{
StringBuilder hex = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
此方法为空字符串生成下一个结果:
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
此结果与来自 AWS Documentation (step 6).
的空字符串的示例哈希值匹配
下一个伪代码来自AWS documentation (section: Task 1, step 7):
payload_hash = HashSHA256(("").Encode("utf-8")).HexDigest()
用于计算GET请求的负载。
为方便起见,此伪代码可以重写为以下方式:
utf8Bytes = ("").Encode("utf-8")
sha256Hash = HashSHA256(utf8Bytes)
payload_hash = sha256Hash.HexDigest()
如何将此伪代码转换为 C#
?
下一个示例 C#
相当于您提供的伪代码:
using System;
using System.Security.Cryptography;
using System.Text;
...
public static void Demo()
{
using (SHA256 sha256 = SHA256.Create())
{
string textToHash = "";
byte[] bytesToHash = Encoding.UTF8.GetBytes(textToHash);
byte[] hash = sha256.ComputeHash(bytesToHash);
string hexDigest = ToHexStr(hash);
Console.WriteLine(hexDigest);
}
}
public static string ToHexStr(byte[] hash)
{
StringBuilder hex = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
此方法为空字符串生成下一个结果:
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
此结果与来自 AWS Documentation (step 6).
的空字符串的示例哈希值匹配