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

本文关键字:字符串 SHA-256 获取 | 更新日期: 2023-09-27 18:17:44

我有一些string,我想用c#用SHA-256哈希函数哈希它。我想要这样写:

 string hashString = sha256_hash("samplestring");

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

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

实现可以是这样的

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核心,.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();
}

从。net 5开始,您可以使用新的Convert.ToHexString方法将哈希字节数组转换为(十六进制)字符串,而不必使用StringBuilder.ToString("X0")等:

public static string HashWithSHA256(string value)
{
  using var hash = SHA256.Create();
  var byteArray = hash.ComputeHash(Encoding.UTF8.GetBytes(value));
  return Convert.ToHexString(byteArray);
}

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

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

简体:

string sha256(string s) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(s)));

我尝试了上述所有方法,但都不适合我。这是我做的一个完美的工作:

public static string Encrypt(string input)
{
    using (SHA256 sha256 = SHA256.Create())
    {
        // Convert the input string to a byte array
        byte[] inputBytes = Encoding.UTF8.GetBytes(input);
        // Compute the hash value of the input bytes
        byte[] hashBytes = sha256.ComputeHash(inputBytes);
        // Convert the hash bytes to a hexadecimal string
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hashBytes.Length; i++)
        {
            sb.Append(hashBytes[i].ToString("x2"));
        }
        return sb.ToString();
    }
}

确保在代码开头使用System.Security.Cryptography

using System.Security.Cryptography