gh-94684: uuid: support bytes in the name argument to uuid3/5 (#94709)

RFC 4122 does not specify that name should be a string, so for completness the functions should also support a name given as a raw byte sequence.
This commit is contained in:
MonadChains 2023-03-24 00:42:43 +01:00 committed by GitHub
parent f1e3eeebc0
commit 413b7db8a4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 43 additions and 6 deletions

View file

@ -711,9 +711,11 @@ def uuid1(node=None, clock_seq=None):
def uuid3(namespace, name):
"""Generate a UUID from the MD5 hash of a namespace UUID and a name."""
if isinstance(name, str):
name = bytes(name, "utf-8")
from hashlib import md5
digest = md5(
namespace.bytes + bytes(name, "utf-8"),
namespace.bytes + name,
usedforsecurity=False
).digest()
return UUID(bytes=digest[:16], version=3)
@ -724,8 +726,10 @@ def uuid4():
def uuid5(namespace, name):
"""Generate a UUID from the SHA-1 hash of a namespace UUID and a name."""
if isinstance(name, str):
name = bytes(name, "utf-8")
from hashlib import sha1
hash = sha1(namespace.bytes + bytes(name, "utf-8")).digest()
hash = sha1(namespace.bytes + name).digest()
return UUID(bytes=hash[:16], version=5)