Hash function that produces short hashes?

后端 未结 10 1713
走了就别回头了
走了就别回头了 2020-12-07 23:58

Is there a way of encryption that can take a string of any length and produce a sub-10-character hash? I want to produce reasonably unique ID\'s but based on message content

10条回答
  •  醉话见心
    2020-12-08 00:21

    Just summarizing an answer that was helpful to me (noting @erasmospunk's comment about using base-64 encoding). My goal was to have a short string that was mostly unique...

    I'm no expert, so please correct this if it has any glaring errors (in Python again like the accepted answer):

    import base64
    import hashlib
    import uuid
    
    unique_id = uuid.uuid4()
    # unique_id = UUID('8da617a7-0bd6-4cce-ae49-5d31f2a5a35f')
    
    hash = hashlib.sha1(str(unique_id).encode("UTF-8"))
    # hash.hexdigest() = '882efb0f24a03938e5898aa6b69df2038a2c3f0e'
    
    result = base64.b64encode(hash.digest())
    # result = b'iC77DySgOTjliYqmtp3yA4osPw4='
    

    The result here is using more than just hex characters (what you'd get if you used hash.hexdigest()) so it's less likely to have a collision (that is, should be safer to truncate than a hex digest).

    Note: Using UUID4 (random). See http://en.wikipedia.org/wiki/Universally_unique_identifier for the other types.

提交回复
热议问题