Search code examples
pythonhashuuidsha256

Convert sha256 digest to UUID in python


Given a sha256 hash of a str in python:

import hashlib

hash = hashlib.sha256('foobar'.encode('utf-8'))

How can the hash be converted to a UUID?

Note: there will obviously be a many-to-one mapping of hexdigest to UUID given that a hexdigest has 2^256 possible values and a UUID has 2^128.

Thank you in advance for your consideration and response.


Solution

  • Given that UUID takes a 32 hex character input string and hexdigest produces 64 characters, a simple approach would be to sub-index the resulting hash digest to achieve the appropriate string length:

    import hashlib
    import uuid
    
    
    hash = hashlib.sha256('foobar'.encode('utf-8'))
    
    uuid.UUID(hash.hexdigest()[::2])