Home  >  Q&A  >  body text

python 用md5生成16位长度字符串,求解

python 用md5生成16位长度字符串,求解

阿神阿神2740 days ago1764

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-18 09:42:58

    Two methods:

    1. Random (to be precise, this is just a function that randomly generates a mixture of letters and numbers of any length)

    import random
    import string
    
    def id_generator(size=16, chars=string.ascii_letters + string.digits):
        return ''.join(random.choice(chars) for _ in range(size))
    
    print(id_generator())
    # 结果 nrICjdPKnxZdp4tI (每次都不同)
    

    2. md5 (this should be the result you want)

    # Python 2.x
    import hashlib
    print hashlib.md5("fuck gfw").hexdigest()[8:-8]
    
    # Python 3.x
    import hashlib
    print(hashlib.md5("fuck gfw".encode('utf-8')).hexdigest())[8:-8]
    

    Attachment: The difference between 16-bit MD5 encryption and 32-bit MD5 encryption

    The md5 encryption is usually a 32-bit encoding. In fact, sometimes it only needs 16 bits. So as you can see, there is one more step to process, just take the middle 16 bits. This kind of living Python is most suitable

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:42:58

    import hashlib
    
    data =  'This a md5 test!'
    hash_md5 = hashlib.md5(data)
    
    hash_md5.hexdigest() # 按16位输出
    

    Output result 'fdedaafb043d41ff06b6ef249ef53be9'

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:42:58

    The simplest way should be:

    >>> import hashlib
    >>> hashlib.md5("test").digest()
    "\t\x8fk\xcdF!\xd3s\xca\xdeN\x83&'\xb4\xf6"

    In this way, 128 bit (16 bit) MD5 is obtained. But it’s not intuitive. I usually use hexadecimal format:

    >>> hashlib.md5("test").hexdigest()
    '098f6bcd4621d373cade4e832627b4f6'

    reply
    0
  • Cancelreply