在python中将sha256摘要转换为UUID

Ram*_*gil 6 python hash uuid sha256

str给定python 中a 的 sha256 哈希值:

import hashlib

hash = hashlib.sha256('foobar'.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

如何将hash转换为 a UUID

2^256注意:鉴于 hexdigest 具有可能的值并且 UUID 具有 ,显然存在 hexdigest 到 UUID 的多对一映射2^128

预先感谢您的考虑和回复。

Ram*_*gil 8

鉴于UUID需要 32 个十六进制字符输入字符串并hexdigest生成 64 个字符,一种简单的方法是对生成的哈希摘要进行子索引以获得适当的字符串长度:

import hashlib
import uuid


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

uuid.UUID(hash.hexdigest()[::2])
Run Code Online (Sandbox Code Playgroud)