user5477154
user5477154

Reputation:

Best way to prepare values of varying types for combined hashing in C#?

I have a few values of varying types which I need to combine together before hashing to create a value that is unique to this combination. Security isn't particularly important, just that the values are guaranteed unique.

Is this a safe approach, and furthermore are there any issues with this approach that I should know about?

public string GetHash(int x, int y, DateTime z, string w)
        {
            string concat = x.ToString() + y.ToString() + z.Ticks.ToString() + w;
            byte[] hash = hashAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(concat));
            return Encoding.ASCII.GetString(hash);
        }

Thanks in advance!

Upvotes: 0

Views: 39

Answers (1)

John Wu
John Wu

Reputation: 52280

No, it's not necessarily reliable, because the system that verifies the hash could have different culture settings. You could address this by adding CultureInfo.InvariantCulture to your ToString() calls.

using System.Globalization
...
string concat = x.ToString(CultureInfo.InvariantCulture)
              + y.ToString(CultureInfo.InvariantCulture)
              + z.Ticks.ToString(CultureInfo.InvariantCulture) 
              + w;

You may also be subject to collisions, since your fields align ambiguously (e.g. "11" + "2" is the same as "1" + "12"). You can address that by adding delimiters or using a fixed width format.

string concat = x.ToString("0000000000", CultureInfo.InvariantCulture)
              + y.ToString("0000000000", CultureInfo.InvariantCulture) 
              + z.Ticks.ToString("0000000000", CultureInfo.InvariantCulture) 
              + w;

Or

string concat = x.ToString(CultureInfo.InvariantCulture)
              + "|"
              + y.ToString(CultureInfo.InvariantCulture)
              + "|"
              + z.Ticks.ToString(CultureInfo.InvariantCulture) 
              + "|"
              + w;

Upvotes: 1

Related Questions