How succeptible to accidental collision is the construct sha256(uuid4 + now) in Python? 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?
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.