55

我有一些string,我想使用 C# 使用SHA-256散列函数对其进行散列。我想要这样的东西:

 string hashString = sha256_hash("samplestring");

框架中是否内置了一些东西来做到这一点?

4

3 回答 3

140

实现可能是这样的

public static String sha256_hash(String value) {
  StringBuilder Sb = new StringBuilder();

  using (SHA256 hash = SHA256Managed.Create()) {
    Encoding enc = Encoding.UTF8;
    Byte[] result = hash.ComputeHash(enc.GetBytes(value));

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

  return Sb.ToString();
}

编辑: Linq实现更简洁,但可能不太可读

public static String sha256_hash(String value) {
  using (SHA256 hash = SHA256Managed.Create()) {
    return String.Concat(hash
      .ComputeHash(Encoding.UTF8.GetBytes(value))
      .Select(item => item.ToString("x2")));
  }
} 

编辑 2: .NET Core、.NET5、.NET6 ...

public static String sha256_hash(string value)
{
    StringBuilder Sb = new StringBuilder();

    using (var hash = SHA256.Create())            
    {
        Encoding enc = Encoding.UTF8;
        byte[] result = hash.ComputeHash(enc.GetBytes(value));

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

    return Sb.ToString();
}
于 2013-06-08T15:57:18.937 回答
3

这是 .net 核心中更好/更整洁的方式:

public static string sha256_hash( string value )
{
  using var hash = SHA256.Create();
  var byteArray = hash.ComputeHash( Encoding.UTF8.GetBytes( value ) );
  return Convert.ToHexString( byteArray ).ToLower();
}
于 2021-09-13T20:32:22.073 回答
0

我正在寻找一个在线解决方案,并且能够从 Dmitry 的回答中编译以下内容:

public static String sha256_hash(string value)
{
    return (System.Security.Cryptography.SHA256.Create()
            .ComputeHash(Encoding.UTF8.GetBytes(value))
            .Select(item => item.ToString("x2")));
}
于 2018-05-29T18:58:19.993 回答