Convert sha256 digest to UUID in python

Viewed 1957

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.

2 Answers

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])

You could create a KDF hash of it first which allows you to choose the desired length of bytes in the hash to fit it into a UUID.

import hashlib
import uuid

uuid.UUID(bytes=hashlib.pbkdf2_hmac('sha256', b'foobar', b'', 10**6, dklen=16))

If this solution works for you, you should determine if a 16-byte KDF compromises any of your security requirements. And, you might want to use a salt too (the third argument to pbkdf2_hmac).

Related