静态方法:SHA256哈希算法
public static string SHA256Hash(string value) { if (string.IsNullOrEmpty(value)) return string.Empty; using (SHA256 sha256Hash = SHA256.Create()) { // Convert the input string to a byte array and compute the hash. byte[] data = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(value)); // Create a new Stringbuilder to collect the bytes // and create a string. StringBuilder sBuilder = new StringBuilder(); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } // Return the hexadecimal string. return sBuilder.ToString(); } }
public static bool VerifySHA256Hash(string input, string hash) { if (string.IsNullOrEmpty(input)) return false; if (string.IsNullOrEmpty(hash)) return false; // Hash the input. string hashOfInput = SHA256Hash(input); // Create a StringComparer an compare the hashes. StringComparer comparer = StringComparer.OrdinalIgnoreCase; if (0 == comparer.Compare(hashOfInput, hash)) { return true; } else { return false; } //return 0 == comparer.Compare(hashOfInput, hash) ? true : false; }