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

时间:2013-06-08 12:05:18

标签: c# string hash sha256

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

 string hashString = sha256_hash("samplestring");

框架内置了一些内容吗?

2 个答案:

答案 0 :(得分:90)

实施可能就像那样

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

答案 1 :(得分: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")));
}
相关问题