Random hash in Python

What is the easiest way to generate a random hash (MD5) in Python?

+76
python hash md5
Jun 10 '09 at 16:05
source share
9 answers

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

import random hash = random.getrandbits(128) print("hash value: %032x" % hash) 

Although I do not see the point. Maybe you should clarify why you need it ...

+113
Jun 10 '09 at 16:09
source share

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

 import uuid uuid.uuid4().hex 

UUID4 gives you a random unique identifier that has the same length as the sum of md5. Hex will be the sixth line instead of returning a uuid object.

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

+69
Nov 19 '13 at 0:18
source share

This works for both python 2.x and 3.x

 import os import binascii print(binascii.hexlify(os.urandom(16))) '4a4d443679ed46f7514ad6dbe3733c3d' 
+41
Mar 22 2018-12-12T00:
source share

The secrets module was added in Python 3.6+. It provides cryptographically secure random values โ€‹โ€‹in a single call. Functions take the optional argument nbytes , defaults to 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' 
+23
Jul 17 '17 at 22:36
source share

Another approach. You do not need to format an int to get it.

 import random import string def random_string(length): pool = string.letters + string.digits return ''.join(random.choice(pool) for i in xrange(length)) 

Gives you flexibility regarding string length.

 >>> random_string(64) 'XTgDkdxHK7seEbNDDUim9gUBFiheRLRgg7HyP18j6BZU5Sa7AXiCHP1NEIxuL2s0' 
+13
Jan 25 '12 at 22:10
source share

Another approach to this particular issue:

 import random, string def random_md5like_hash(): available_chars= string.hexdigits[:16] return ''.join( random.choice(available_chars) for dummy in xrange(32)) 

I do not say this faster or preferable to any other answer; just that this is a different approach :)

+5
Jun 11 '09 at 22:52
source share
 import uuid from md5 import md5 print md5(str(uuid.uuid4())).hexdigest() 
+4
Jul 26 '13 at 18:03
source share
 import os, hashlib hashlib.md5(os.urandom(32)).hexdigest() 
+1
May 30 '17 at 23:44
source share
 from hashlib import md5 plaintext = input('Enter the plaintext data to be hashed: ') # Must be a string, doesn't need to have utf-8 encoding ciphertext = md5(plaintext.encode('utf-8').hexdigest()) print(ciphertext) 

It should also be noted that MD5 is a very weak hash function, collisions were also detected (two different plaintext values โ€‹โ€‹result in the same hash). Just use a random value for plaintext .

0
Feb 24 '19 at 19:23
source share



All Articles