Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET SHA256 Vs Object.GetHashCode()

Tags:

c#

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
        }
    }
like image 748
David Klempfner Avatar asked Oct 28 '25 16:10

David Klempfner


1 Answers

You cannot compare the two as they are built for two entirely different purposes. What is your goal? - Encryption or simple object lookup?

For object lookup (in a hashtable): GetHashCode()

For encryption: SHA256 combined with e.g. AES.

GetHashCode() should be overridden for your type and ideally only use immutable fields, ie. fields not changing over the lifetime of the object, read-only fields is a good example of this ;-)

SHA256 is used for example to hash a password for usage in an encryption algorithm that takes 256-bit keys. The point of a hashing algorithm used for encryption is that it must be slow (the opposite of the object lookup scenario) to make it more difficult to bruteforce attack passwords.

So no pros/cons as such, but really depends on your goal. Use the right tool for the purpose :-)

like image 197
Bo Stig Christensen Avatar answered Oct 31 '25 06:10

Bo Stig Christensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!