In this article, we will see how to implement a function that will generate a random hash of the specified format with the given length.
The below function generates the random hash of the following formats.
- Alpha numeric
- Apha lower with special characters included (_-).
- Alpha
- Alpha numeric lower
- Hexadecimal
- Numeric
- Numeric with non zero
import random
import string
def random_hash(format: str, length: int) -> str:
pool = ""
if format == "alnum":
pool = string.digits + string.ascii_letters
elif format == "alpSpecLower":
pool = string.ascii_lowercase + "-_"
elif format == "alpha":
pool = string.ascii_letters
elif format == "alpNumLower":
pool = string.digits + string.ascii_lowercase
elif format == "hexdec":
pool = string.hexdigits[:-6]
elif format == "numeric":
pool = string.digits
elif format == "nozero":
pool = "123456789"
else:
return ""
# allocate a new list to store the hash
buf = [random.choice(pool) for _ in range(length)]
random.shuffle(buf)
return "".join(buf)
print("alnum : " + random_hash("alnum", 10))
print("alpSpecLower : " + random_hash("alpSpecLower", 10))
print("alpha : " + random_hash("alpha", 10))
print("alpNumLower : " + random_hash("alpNumLower", 10))
print("hexdec : " + random_hash("hexdec", 10))
print("numeric : " + random_hash("numeric", 10))
print("nozero : " + random_hash("nozero", 10))
Explanation:
- The above function takes two arguments:
format
andlength
, whereformat
is a string that specifies the type of characters to use in the hash, andlength
is an integer that specifies the length of the hash. - The first thing the function does is define an empty string
pool
. This string will be populated with the characters that are allowed for the given format. - The function then uses an
if-elif-else
statement to populatepool
based on the value offormat
. Ifformat
is not one of the specified formats, the function returns an empty string. - Next, the function initializes a list
buf
of lengthlength
. This list will store the characters of the generated hash. - The
buf
list is filled with random characters frompool
using a list comprehension. Each character is chosen randomly using therandom.choice
function. - Finally, the
buf
list is shuffled using therandom.shuffle
function, and the shuffled list is converted to a string using thejoin
method and the resultant string is returned as the output of the function.
Leave a Comment