小编典典

获取字符串的SHA-256字符串

c#

我有一些string,我想 哈希值 与它 SHA-256 采用C#哈希函数。我想要这样的东西:

 string hashString = sha256_hash("samplestring");

框架中是否有内置的工具可以做到这一点?


阅读 1145

收藏
2020-05-19

共1个答案

小编典典

实现可能是这样的

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

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();
}
2020-05-19