1
$\begingroup$

I need 32 byte pseudorandom sequences that denote unique filenames and am currently using this Python code:

import base64
import hashlib
from django.utils import timezone
from uuid import uuid4

def get_name():
    data = str(uuid4()) + str(timezone.now())
    hash = base64.b64encode(hashlib.sha256(
                  data.encode()).digest(), '-_'.encode()).decode()[:-1]

Do you think it's necessary to check if the generated sequence doesn't collide with any previously generated sequences or can I just skip the overhead of checking, trusting the function?

$\endgroup$
4
  • 1
    $\begingroup$ What is your threat model? Are you only worried about accidental collisions or are you worried that an adversary, knowing all details of the system, would be able to force a collision? $\endgroup$
    – mikeazo
    Mar 24, 2016 at 14:19
  • $\begingroup$ There are two basic threats: the first and foremost (which I am worried about) is accidental collision. And yes, another one is adversary guessing the sequence (this would allow him to act without authority) but I don't think it is very likely. $\endgroup$
    – Crossfire
    Mar 24, 2016 at 14:31
  • 4
    $\begingroup$ It's at least not worse than a GUID by itself, which should be good enough even without any additional inputs. Personally I'd throw in an extra 32 bytes read from SystemRandom. $\endgroup$ Mar 24, 2016 at 14:39
  • $\begingroup$ Thanks for the tip. I've added SystemRandom to the mix $\endgroup$
    – Crossfire
    Mar 24, 2016 at 15:01

1 Answer 1

3
$\begingroup$

You can skip the test, unless you suspect that uuid4()) + str(timezone.now() (and the random value you may have added) is possibly not unique. The chances that SHA-256 itself accidentally introduces a collision is negligibly small.

There are no known attacks on SHA-256 that break the algorithm, other than length extension attacks. Those however don't seem to be an issue with your protocol.

So you mainly have to worry about an attacker messing with your input. The date won't add much entropy, so as a long as the underlying random generator(s) are secure, your scheme is likely secure as well.


Although it doesn't seem to be an issue with your current scheme, you should make sure that the input to the hash function doesn't rely on the size of the input data. For instance, A | BC hashes to the save value as AB | C. In other words, you need a canonical method of encoding your data structure. Best to document this, otherwise you may mess up your scheme at a later date.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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