Random hash in Python

I think what you are looking for is a universal unique identifier.Then the module UUID in python is what you are looking for.

import uuid
uuid.uuid4().hex

UUID4 gives you a random unique identifier that has the same length as a md5 sum. Hex will represent is as an hex string instead of returning a uuid object.

http://docs.python.org/2/library/uuid.html

https://docs.python.org/3/library/uuid.html


A md5-hash is just a 128-bit value, so if you want a random one:

import random

hash = random.getrandbits(128)

print("hash value: %032x" % hash)

I don't really see the point, though. Maybe you should elaborate why you need this...


The secrets module was added in Python 3.6+. It provides cryptographically secure random values with a single call. The functions take an optional nbytes argument, default is 32 (bytes * 8 bits = 256-bit tokens). MD5 has 128-bit hashes, so provide 16 for "MD5-like" tokens.

>>> import secrets

>>> secrets.token_hex(nbytes=16)
'17adbcf543e851aa9216acc9d7206b96'

>>> secrets.token_urlsafe(16)
'X7NYIolv893DXLunTzeTIQ'

>>> secrets.token_bytes(128 // 8)
b'\x0b\xdcA\xc0.\x0e\x87\x9b`\x93\\Ev\x1a|u'

Tags:

Python

Hash

Md5