tags:

views:

983

answers:

2

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
+1 for not computing a relatively expensive hash from a random number: this approach is 5x faster.
NicDumZ
+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
the random.seed() call is useless, more or less.
ΤΖΩΤΖΙΟΥ
I would've used os.urandom because wanting an MD5 hash might mean wanting a secure one.
Unknown
Nice use of the hex format specification to print. +1
Jarret Hardie
+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 :)

ΤΖΩΤΖΙΟΥ