在使用SHA256和Object.GetHashCode()时,各有优缺点。
下面的代码中,两种方法的输出结果相同,然而GetHashCode()方法更简单,需要较少的对象/代码。
class Program
{
static void Main(string[] args)
{
TestGetHashCode();
TestSha256();
Console.Read();
}
static void TestSha256()
{
Console.WriteLine("Testing SHA256");
UnicodeEncoding byteConverter = new UnicodeEncoding();
SHA256 sha256 = SHA256.Create();
string data = "A paragraph of text";
byte[] hashA = sha256.ComputeHash(byteConverter.GetBytes(data));
data = "A paragraph of changed text";
byte[] hashB = sha256.ComputeHash(byteConverter.GetBytes(data));
data = "A paragraph of text";
byte[] hashC = sha256.ComputeHash(byteConverter.GetBytes(data));
Console.WriteLine(hashA.SequenceEqual(hashB)); // Displays: false
Console.WriteLine(hashA.SequenceEqual(hashC)); // Displays: true
}
static void TestGetHashCode()
{
Console.WriteLine("Testing Object.GetHashCode()");
string data = "A paragraph of text";
int hashA = data.GetHashCode();
data = "A paragraph of changed text";
int hashB = data.GetHashCode();
data = "A paragraph of text";
int hashC = data.GetHashCode();
Console.WriteLine(hashA.Equals(hashB)); // Displays: false
Console.WriteLine(hashA.Equals(hashC)); // Displays: true
}
}
Object.GetHashCode
在两次应用程序运行之间可能会产生不同的结果。而 SHA-xx 在多次运行中是稳定的,被明确定义,可以跨平台使用。 - Caramiriel