User987
User987

Reputation: 3823

Generating a unique Hash based on DateTime and String parameter

I would like to create a function which would enable me to generate unique values always based on these two entry parameters:

public string ReturnUniqueValue(DateTime date, string ID)
{
 // Logic here
}

The date parameter is in the following format:

2017-08-14 11:55:32.00

While the ID is in the following format:

112452573848

I would like to generate a unique hash which is 40 characthers in length and that it never repeats.

Is this doable with datetime parameter + unique id string ?

I figured that datetime is never the same (it's nearly impossible), thus this should be able to always generate unique value?

Upvotes: 3

Views: 10672

Answers (1)

Axel Heer
Axel Heer

Reputation: 1883

You can

  • write all your parameters (whichever) into a stream
  • compute a hash using your favorite algorithm (e.g. SHA265)
  • and return its first 20 values (= 40 characters) as a final result

In code:

public string ReturnUniqueValue(DateTime date, string ID)
{
    var result = default(byte[]);

    using (var stream = new MemoryStream())
    {
        using (var writer = new BinaryWriter(stream, Encoding.UTF8, true))
        {
            writer.Write(date.Ticks);
            writer.Write(ID);
        }

        stream.Position = 0;

        using (var hash = SHA256.Create())
        {
            result = hash.ComputeHash(stream);
        }
    }

    var text = new string[20];

    for (var i = 0; i < text.Length; i++)
    {
        text[i] = result[i].ToString("x2");
    }

    return string.Concat(text);
}

Note: if you just want a single unique value for multiple parameters, a simple concatenation should already do it. Since you explicitly asked for a "hash" with 40 characters, this more elaborate solution may fit somehow better.

Attention: extending this to more parameters of the same type (e.g. two strings) should include the parameters position within the stream to avoid collisions ((a, b) != (b, a)).

Upvotes: 6

Related Questions