160

我尝试使用 SHA256 对字符串进行哈希处理,我正在使用以下代码:

using System;
using System.Security.Cryptography;
using System.Text;
 public class Hash
    {
    public static string getHashSha256(string text)
    {
        byte[] bytes = Encoding.Unicode.GetBytes(text);
        SHA256Managed hashstring = new SHA256Managed();
        byte[] hash = hashstring.ComputeHash(bytes);
        string hashString = string.Empty;
        foreach (byte x in hash)
        {
            hashString += String.Format("{0:x2}", x);
        }
        return hashString;
    }
}

但是,与我的朋友 php 以及在线生成器(例如This generator)相比,此代码给出了明显不同的结果

有谁知道错误是什么?不同的基地?

4

7 回答 7

167
于 2012-09-13T23:50:01.037 回答
115

我也遇到了另一种实现方式的问题,但我忘记了我从哪里得到它,因为它是 2 年前的。

static string sha256(string randomString)
{
    var crypt = new SHA256Managed();
    string hash = String.Empty;
    byte[] crypto = crypt.ComputeHash(Encoding.ASCII.GetBytes(randomString));
    foreach (byte theByte in crypto)
    {
        hash += theByte.ToString("x2");
    }
    return hash;
}

当我abcdefghi2013出于某种原因输入类似内容时,它会给出不同的结果并导致我的登录模块出现错误。然后我尝试按照 Quuxplusone 建议的相同方式修改代码,并将编码从 更改ASCIIUTF8然后它终于起作用了!

static string sha256(string randomString)
{
    var crypt = new System.Security.Cryptography.SHA256Managed();
    var hash = new System.Text.StringBuilder();
    byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(randomString));
    foreach (byte theByte in crypto)
    {
        hash.Append(theByte.ToString("x2"));
    }
    return hash.ToString();
}

再次感谢 Quuxplusone 的精彩而详细的回答!:)

于 2013-02-05T14:33:36.023 回答
12
public static string ComputeSHA256Hash(string text)
{
    using (var sha256 = new SHA256Managed())
    {
        return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
    }                
}

你得到不同结果的原因是你没有使用相同的字符串编码。您为计算 SHA256 的在线网站放置的链接使用 UTF8 编码,而在您的示例中,您使用了 Unicode 编码。它们是两种不同的编码,因此您不会得到相同的结果。通过上面的示例,您可以获得链接网站的相同 SHA256 哈希值。您还需要在 PHP 中使用相同的编码。

每个软件开发人员绝对、绝对必须了解 Unicode 和字符集的绝对最低要求(没有借口!)

https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/

于 2019-11-27T23:13:26.827 回答
6

有史以来最短和最快的方式。只有1行!

public static string StringSha256Hash(string text) =>
    string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);
于 2020-05-18T19:26:19.180 回答
5

在 PHP 版本中,您可以在最后一个参数中发送“true”,但默认为“false”。以下算法等效于将 'sha256' 作为第一个参数传递时的默认 PHP 哈希函数:

public static string GetSha256FromString(string strData)
    {
        var message = Encoding.ASCII.GetBytes(strData);
        SHA256Managed hashString = new SHA256Managed();
        string hex = "";

        var hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }
于 2015-01-13T11:07:38.420 回答
5
public string EncryptPassword(string password, string saltorusername)
        {
            using (var sha256 = SHA256.Create())
            {
                var saltedPassword = string.Format("{0}{1}", salt, password);
                byte[] saltedPasswordAsBytes = Encoding.UTF8.GetBytes(saltedPassword);
                return Convert.ToBase64String(sha256.ComputeHash(saltedPasswordAsBytes));
            }
        }
于 2019-09-23T07:00:05.157 回答
-4

这在 .NET Core 3.1 中对我有用。
但不在 .NET 5 预览版 7 中。

using System;
using System.Security.Cryptography;
using System.Text;

namespace PortalAplicaciones.Shared.Models
{
    public class Encriptar
    {
        public static string EncriptaPassWord(string Password)
        {
            try
            {
                SHA256Managed hasher = new SHA256Managed();

                byte[] pwdBytes = new UTF8Encoding().GetBytes(Password);
                byte[] keyBytes = hasher.ComputeHash(pwdBytes);

                hasher.Dispose();
                return Convert.ToBase64String(keyBytes);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }  
    }
}
 
于 2020-07-29T11:40:27.487 回答