Random hash in Python

后端 未结 9 1667
陌清茗
陌清茗 2020-12-23 13:11

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

相关标签:
9条回答
  • 2020-12-23 13:23

    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...

    0 讨论(0)
  • 2020-12-23 13:24

    Yet another approach. You won't have 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 on the length of the string.

    >>> random_string(64)
    'XTgDkdxHK7seEbNDDUim9gUBFiheRLRgg7HyP18j6BZU5Sa7AXiCHP1NEIxuL2s0'
    
    0 讨论(0)
  • 2020-12-23 13:30
    import uuid
    from md5 import md5
    
    print md5(str(uuid.uuid4())).hexdigest()
    
    0 讨论(0)
  • 2020-12-23 13:33

    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'
    
    0 讨论(0)
  • 2020-12-23 13:36

    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

    0 讨论(0)
  • 2020-12-23 13:36

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

    import os
    import binascii
    print(binascii.hexlify(os.urandom(16)))
    '4a4d443679ed46f7514ad6dbe3733c3d'
    
    0 讨论(0)
提交回复
热议问题