What are the pros/cons when it comes to using SHA256 Vs Object.GetHashCode()?
In the code below, the output is identical for both methods, however the GetHashCode() seems a lot simpler, requires fewer objects/code.
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.GetHashCodecan give different results between two application runs. SHA-xx is stable over multiple runs and is well defined so that it can be used cross-platform.