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

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

  string hashString = sha256_hash("samplestring"); 

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

实施可能就是这样

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

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

 public static String sha256_hash(string value) { return (System.Security.Cryptography.SHA256.Create() .ComputeHash(Encoding.UTF8.GetBytes(value)) .Select(item => item.ToString("x2"))); }