Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Generating hash ids using uuid3() and uuid5() in Python
The universally unique identifier (UUID) is a 128-bit hexadecimal number that guarantees uniqueness within a given namespace. Python's uuid module provides uuid3() and uuid5() functions to generate hash-based UUIDs from a namespace and name string.
Syntax
uuid.uuid3(namespace, name) uuid.uuid5(namespace, name)
Both functions take two parameters:
- namespace − A UUID object defining the namespace
- name − A string used to generate the UUID
Key Differences
| Function | Hash Algorithm | Security | Use Case |
|---|---|---|---|
uuid3() |
MD5 | Lower | General purpose |
uuid5() |
SHA-1 | Higher | Security-sensitive applications |
Common Namespaces
Python provides predefined namespaces for common use cases:
-
NAMESPACE_DNS− For fully qualified domain names -
NAMESPACE_URL− For URLs -
NAMESPACE_OID− For ISO OIDs -
NAMESPACE_X500− For X.500 DNs
Example
Here's how to generate hash-based UUIDs using both functions ?
import uuid
# Test strings
domain = "www.tutorialspoint.com"
url = "http://www.tutorialspoint.com"
print("Using uuid3 with DNS namespace:")
print(uuid.uuid3(uuid.NAMESPACE_DNS, domain))
print("\nUsing uuid3 with URL namespace:")
print(uuid.uuid3(uuid.NAMESPACE_URL, url))
print("\nUsing uuid5 with DNS namespace:")
print(uuid.uuid5(uuid.NAMESPACE_DNS, domain))
print("\nUsing uuid5 with URL namespace:")
print(uuid.uuid5(uuid.NAMESPACE_URL, url))
Using uuid3 with DNS namespace: 0c4b6e50-3630-3d98-a85a-2cd08cf4b8a6 Using uuid3 with URL namespace: e5051d13-d1a5-381a-bc21-5017b275a7f2 Using uuid5 with DNS namespace: 7cfc74e5-0b25-524f-95a1-a2e7b4b3b780 Using uuid5 with URL namespace: a064f94e-5ff6-51e4-88e2-e2163a79abce
Deterministic Nature
Hash-based UUIDs are deterministic − the same namespace and name always produce the same UUID ?
import uuid
name = "example.com"
# Generate the same UUID multiple times
id1 = uuid.uuid5(uuid.NAMESPACE_DNS, name)
id2 = uuid.uuid5(uuid.NAMESPACE_DNS, name)
print("First generation:", id1)
print("Second generation:", id2)
print("Are they equal?", id1 == id2)
First generation: 15f94308-821c-5972-a0a8-d8c50b8b71c6 Second generation: 15f94308-821c-5972-a0a8-d8c50b8b71c6 Are they equal? True
Conclusion
Use uuid3() and uuid5() when you need deterministic UUIDs based on existing data. Choose uuid5() for better security, and select the appropriate namespace for your use case.
Advertisements
