我如何将此HashSHA256((“”)。Encode(“ utf-8”))。HexDigest()转换为C#?

问题描述 投票:-1回答:1

该代码来自AWS,示例为伪代码。谁能帮我用C#创建代码?

utf8Bytes = ("").Encode("utf-8")
sha256Hash = HashSHA256(utf8Bytes)
hexResult = sha256Hash.HexDigest()
c# hash cryptography sha256
1个回答
0
投票

我认为下一个示例与您提供的伪代码在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();
}
© www.soinside.com 2019 - 2024. All rights reserved.