Open In App

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

Last Updated : 21 Sep, 2021
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 : 
 

Python3




# Python3 code to demonstrate working
# of uuid3() and uuid5()
import uuid
 
# initializing a string
 
# using NAMESPACE_URL as namespace
# to generate MD5 hash uuid
print ("The SHA1 hash value generated ID is : ",
            uuid.uuid3(uuid.NAMESPACE_URL, url))
 
# using NAMESPACE_URL as namespace 
# to generate SHA-1 hash uuid
print ("The MD5 hash value generated ID is : ",
            uuid.uuid5(uuid.NAMESPACE_URL, url))


Output: 

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

 

 
Code #2 : 
 

Python3




# 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 find MD5 hash id
print ("The SHA1 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 MD5 hash value generated ID is : ",
    uuid.uuid5(uuid.NAMESPACE_DNS, qualified_dns))


Output: 

The SHA1 hash value generated ID is :  adbed9f7-bbe3-376f-b88d-2018b8f6db07
The MD5 hash value generated ID is :  f72cdf8a-b361-50b2-9451-37a997f8675d

 

  
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