What is the easiest way to generate a random hash (MD5) in Python?
+10
A:
A md5-hash is just a 128-bit value, so if you want a random one:
import random
random.seed()
hash = random.getrandbits(128)
print "hash value: %016x" % hash
I don't really see the point, though. Maybe you should elaborate why you need this...
sth
2009-06-10 16:09:12
+1 for not computing a relatively expensive hash from a random number: this approach is 5x faster.
NicDumZ
2009-06-11 01:36:00
+1 - surely this is better than my answer, can be used also like this: hex(random.getrandbits(128))[2:-1] this gives you same output as md5 hexdigest method.
Jiri
2009-06-11 08:14:04
the random.seed() call is useless, more or less.
ΤΖΩΤΖΙΟΥ
2009-06-11 22:46:56
I would've used os.urandom because wanting an MD5 hash might mean wanting a secure one.
Unknown
2009-06-11 22:58:33
Nice use of the hex format specification to print. +1
Jarret Hardie
2009-06-11 23:00:14
+1
A:
Another approach to this specific question:
import random, string
def random_md5like_hash():
available_chars= string.hexdigits[:16]
return ''.join(
random.choice(available_chars)
for dummy in xrange(32))
I'm not saying it's faster or preferable to any other answer; just that it's another approach :)
ΤΖΩΤΖΙΟΥ
2009-06-11 22:52:23