Open In App

Generating hash id’s using uuid3() and uuid5() in Python

Last Updated : 21 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python’s UUID class defines four functions and each generates different version of UUIDs. Let’s see how to generate UUID based on MD5 and SHA-1 hash using uuid3() and uuid5() .
Cryptographic hashes can be used to generate different ID’s taking NAMESPACE identifier and a string as input. The functions that support cryptographic hash generation are : 

  1. uuid3(namespace, string) : This function uses MD5 hash value of namespaces mentioned with a string to generate a random id of that particular string.
  2. uuid5(namespace, string) : This function uses SHA-1 hash value of namespaces mentioned with a string to generate a random id of that particular string.


uuid module defines the following namespace identifiers for use with uuid3() or uuid5() : 
 

NAMESPACE_DNS : Used when name string is fully qualified domain name. 
NAMESPACE_URL : Used when name string is a URL. 
NAMESPACE_OID : Used when name string is an ISO OID. 
NAMESPACE_X500 : Used when name string is an X.500 DN in DER or a text output format. 
 


Code #1 : 
 

Python
# Python3 code to demonstrate working 
# of uuid3() and uuid5()
import uuid

# initializing a string
url = "https://www.geeksforgeeks.org/fibonacci-sum-subset-elements/"

# using NAMESPACE_URL as namespace 
# to generate MD5 hash uuid
print ("The MD5 hash value generated ID is : ", 
            uuid.uuid3(uuid.NAMESPACE_URL, url))

# using NAMESPACE_URL as namespace 
# to generate SHA-1 hash uuid
print ("The SHA-1 hash value generated ID is : ", 
            uuid.uuid5(uuid.NAMESPACE_URL, url))

Output
The MD5 hash value generated ID is :  e13a319e-16d9-3ff5-a83c-96564007998e
The SHA-1 hash value generated ID is :  dbe3178d-4b83-5024-9b26-9b8e1b280514

 
Code #2 : 
 

Python
# Python3 code to demonstrate working  
# of uuid3() and uuid5()
import uuid

# initializing a string
qualified_dns = "www.geeksforgeeks.org"

# using NAMESPACE_DNS as namespace
# to generate MD5 hash id
print ("The MD5 hash value generated ID is : ", 
    uuid.uuid3(uuid.NAMESPACE_DNS, qualified_dns))

# using NAMESPACE_DNS as namespace 
# to generate SHA-1 hash id
print ("The SHA1 hash value generated ID is : ", 
    uuid.uuid5(uuid.NAMESPACE_DNS, qualified_dns))

Output
The MD5 hash value generated ID is :  d33e89a5-c12e-3a98-bce2-982b91ec3f76
The SHA1 hash value generated ID is :  9d725972-6f05-547c-8a57-1063b2aef945

  
Note : The ID generation is 2 step process. First, the concatenation of string and namespaces takes place, then given as input to the respective function to return a 128 UUID generated. If the same NAMESPACE value with a similar string is chosen again, ID generated will be same as well.
 
Reference : https://docs.python.org/2/library/uuid.html
 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads