I need to create an unique token for a web service. I'm doing that in the following in the following way:

var element_id  // auto increment number, every time different
var secret_key  // an secret key
var random_key  // a random generated string of 8 chars, every time different
var timestamp   // the timestamp at the moment of generation

var token = element_id + secret_key + random_key + timestamp;

This will produce a string consisting of 15 to 20 characters. In my system every string generated in this way is unique.

Then I create the SHA-256 version of that string

var sha256_token=sha256(token);

Will the sha256_token be unique in my system as it was the "clear" token?

  • 2
    $\begingroup$ I guess that the protocol has some overkill if it has a secret and an element_id that is "every time different" - that's all you need for creating a token. However, getting element_id to be different every time on a distributed system can be harder than initially expected (failover, reboots, single point of failure etc. etc.). $\endgroup$ – Maarten Bodewes May 13 '20 at 12:36

Yes, the hash will be unique every time - if the input string is unique every time.

This follows trivially from SHA-256's collision resistance: If your input strings are different but the outputs are the same it's a collision in SHA-256 which would be a huge surprise to find for everyone and a publication-worthy result.

Now the more interesting question is whether your input string will be unique every time. If everything is fixed length - except perhaps the counter - then yes, it will be unique. If the secret key is variable length there may be "unlucky" situations where the last byte of the counter matches the first byte of the secret key and the allocations which belongs where are different (i.e. whether the byte belongs to the counter or the secret key). The "safest" choice here would be to pad everything (except one of the values) to a fixed upper bound length.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.