Flowpoke Flowpoke - 4 months ago 16
Python Question

Whats more random, hashlib or urandom?

I'm working on a project with a friend where we need to generate a random hash. Before we had time to discuss, we both came up with different approaches and because they are using different modules, I wanted to ask you all what would be better--if there is such a thing.

hashlib.sha1(str(random.random())).hexdigest()


or

os.urandom(16).encode('hex')


Typing this question out has got me thinking that the second method is better. Simple is better than complex. If you agree, how reliable is this for 'randomly' generating hashes? How would I test this?

Answer

This solution:

os.urandom(16).encode('hex')

is the best since it uses the OS to generate randomness which should be usable for cryptographic purposes (depends on the OS implementation).

random.random() generates pseudo-random values.

Hashing a random value does not add any new randomness.

Comments