I am trying to compute 8-character short unique random filenames for, let\'s say, thousands of files without probable name collision. Is this method safe enough?
Is there a reason you can't use tempfile
to generate the names?
Functions like mkstemp
and NamedTemporaryFile
are absolutely guaranteed to give you unique names; nothing based on random bytes is going to give you that.
If for some reason you don't actually want the file created yet (e.g., you're generating filenames to be used on some remote server or something), you can't be perfectly safe, but mktemp
is still safer than random names.
Or just keep a 48-bit counter stored in some "global enough" location, so you guarantee going through the full cycle of names before a collision, and you also guarantee knowing when a collision is going to happen.
They're all safer, and simpler, and much more efficient than reading urandom
and doing an md5
.
If you really do want to generate random names, ''.join(random.choice(my_charset) for _ in range(8))
is also going to be simpler than what you're doing, and more efficient. Even urlsafe_b64encode(os.urandom(6))
is just as random as the MD5 hash, and simpler and more efficient.
The only benefit of the cryptographic randomness and/or cryptographic hash function is in avoiding predictability. If that's not an issue for you, why pay for it? And if you do need to avoid predictability, you almost certainly need to avoid races and other much simpler attacks, so avoiding mkstemp
or NamedTemporaryFile
is a very bad idea.
Not to mention that, as Root points out in a comment, if you need security, MD5 doesn't actually provide it.