简单哈希:
public string GetSHA256Hash(string s)
{
if (string.IsNullOrEmpty(s))
{
throw new ArgumentException("An empty string value cannot be hashed.");
}
Byte[] data = System.Text.Encoding.UTF8.GetBytes(s);
Byte[] hash = new SHA256CryptoServiceProvider().ComputeHash(data);
return Convert.ToBase64String(hash);
}
就像其他人所说,有很多选择。
这里是一些示例代码(使用 MD5 而不是 SHA)来自 Microsoft,可能会帮助您入门。
using System;
using System.Security.Cryptography;
using System.Text;
string sSourceData;
byte[] tmpSource;
byte[] tmpHash;
sSourceData = "MySourceData";
//Create a byte array from source data.
tmpSource = ASCIIEncoding.ASCII.GetBytes(sSourceData);
//Compute hash based on source data.
tmpHash = new MD5CryptoServiceProvider().ComputeHash(tmpSource);
在哈希方面,System.Security.Cryptography中有几种支持的算法,对于您的用例,您可能想选择基于SHA的哈希或类似的东西。
关于比较:您不会比较DB值和用户提供给您的值。您使用与首次将密码存储在DB中时使用的相同的加密/哈希函数,这次使用用户输入。如果结果等于DB中的哈希,则密码(可能)正确。
意图是没有任何可以访问DB的人可以以明文检索密码,甚至您的程序也不需要知道它(只有接受用户输入的部分会短暂拥有它)。
链接(甚至可能重复):