The Wayback Machine - https://web.archive.org/web/20240607235658/https://www.geeksforgeeks.org/full-domain-hashing-with-variable-hash-size-in-python/
Open In App

Full domain Hashing with variable Hash size in Python

Last Updated : 11 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

A cryptographic hash function is a special class of hash function that has certain properties which make it suitable for use in cryptography. It is a mathematical algorithm that maps data of arbitrary size to a bit string of a fixed size (a hash function) which is designed to also be a one-way function, that is, a function which is infeasible to invert. In this article, let us understand one such type of hashing with variable hash size. 
Traditional RSA Signature schemes are based on the following sequence of steps: 
 

  1. Obtain the message to be digitally signed – M
  2. Use SHA or some other hashing algorithm to generate the message digest – H = Hash(M)
  3. Encrypt the message digest using the signer’s private key. The encryption results is the signature of the message – S = E(PrivateKey, H)


One potential deficit in the above-illustrated scheme is that the RSA system ends up being underutilized. Let us assume that the RSA modulus is of the order of 2048 bits. This means that the input can be any value with up to 2048 bits. However, in the signature scheme, the input to the RSA system is consistently the same size, the size of the hash-digest. Therefore, if, for instance, SHA-512 is being utilized in the signature scheme, all inputs to the RSA function will consistently be 512 bits. This leaves the majority (> 99% in this case) of the RSA input space unutilized. This has the effect of reducing the overall security level of the RSA system as a result of the input space underutilization.
 


The Full Domain Hashing (FDH) scheme in RSA Signature schemes mitigates this underutilization by hashing the message onto the full domain of the RSA cryptosystem. The goal of FDH, therefore, is:
 

Hash a message using a function whose image-size/digest-size equals the size of the RSA modulus 
 


The two basic approaches to realize a function which can produce an arbitrary size digest are: 
 

  1. Repeatedly hashing the message (with slight modifications) and concatenating
  2. Using an eXtendible Output Function (XOF) hashing methods


Repeated Hashing with Concatenation
Although traditional hashing algorithms such as SHA1, SHA256, SHA512 do not nearly have the sufficient range to cover the input domains of RSA systems, we can construct a full domain hashing method through the repeated application of these hash functions. The standard hash function, say SHA512, is applied to the message repeatedly, concatenating the results each time. This is done until the requisite number of bits is achieved.
To introduce the randomized behaviour of hash functions, instead of hashing the same message repeatedly, some modifications are introduced to the message at each iteration before performing the hashing. An example of such a modification would be to concatenate the iteration count to the message, before hashing. Thus, an FDH function is realized as: 
FDH(m) =\ h(m\lvert\lvert0)\ ||\ h(m||1)\ ||\ h(m||2)\ || \dotso
If the SHA512 hash was computed and concatenated N times, the overall hash will have a bit size of N * 512. Assuming that this value is greater than the required number, ‘K’, of bits, we can extract the leading K bits to obtain the desired length hash.
Below is the implementation of the above approach:
 

Python3

# Python program to demonstrate
# repeated hashing with
# concatenation
 
import binascii
from math import ceil
from hashlib import sha256
 
# Function to perform Full Domain
# Hash of 'message' using
# SHA512 with a digest of
# N bits
def fdh(message, n):
     
 
    result = []
 
    # Produce enough SHA512 digests
    # to make a composite digest
    # greater than or equal to N bits
    for i in range(ceil(n / 256)):
 
        # Append iteration count
        # to the message
        currentMsg = str(message) + str(i)
 
        # Add current hash to results list
        result.append(sha256((currentMsg).encode()).hexdigest())
 
    # Append all the computed hashes
    result = ''.join(result)
 
    # Obtaining binary representating
    resAsBinary = ''.join(format(ord(x), 'b') for x in result)
 
    # Trimming the hash to the
    # required size by taking
    # only the leading bits
    resAsBinary = resAsBinary[:n]
 
    # Converting back to the
    # ASCII from binary format
    return binascii.unhexlify('00%x' % int(resAsBinary, 2)).hex()
 
# Driver code
if __name__ == '__main__':
    # Message to be hashed
    message = "GeeksForGeeks"
 
    # Generate a 600 bit
    # hash using SHA256
    print(fdh(message, 600))

                    

Output: 

00cf161c36df4db9e30d79cf9cb3d72e1934cbaeb9eb8638f0d71f1872679e1df9c3932c77c70c98efa64d34e3166c5b698738b36d9b36b87261c5ae3c61873c98e19b362db1c73658f0e4c9 

 

Using an eXtendible Output Function (XOF) hashing methods
eXtendible Output Functions are a class of hashing functions which, unlike traditional hashing functions, can generate an arbitrarily large sequence of bits in the digest of a message. This is in strong contrast to regular hash functions which are defined by a fixed output size. In the recently introduced SHA-3 scheme, XOF is provided using the SHAKE128 and SHAKE256 algorithms. They follow from the general properties of the sponge construction. A sponge function can generate an arbitrary length of the output. The 128 and 256 in their names indicate its maximum security level (in bits), as described in Sections A.1 and A.2 of FIPS 202.
To avail the functionality of SHA-3 in Python, the PyCryptodome library may be utilized as follows:
 

Python3

# Python program to demonstrate
# the SHA-3 algorithm
 
from Crypto.Hash import SHAKE256
from binascii import hexlify
 
# Instantiate the SHAKE256 object
shake = SHAKE256.new()
 
# Set the message to be hashed
shake.update(b'GeeksForGeeks')
 
# Print a hash output of 50 bits size
print(hexlify(shake.read(50)))

                    

Output: 
 

b’65d6df8d88198de69b3cf59b859d72971b93f102ca20af812b931714a558c7a134cb3bb085835f470c890bd1d50928355358′ 
 


Note: The above code won’t be run on online IDE’s because online IDE’s lack the Crypto library. 
 



Similar Reads

A Cryptographic Introduction to Hashing and Hash Collisions
What is hashing?Hashing is the process of converting any kind of data (usually passwords or installer files) into a fixed-length string. There are multiple types of hashes, but for this article, we will look only at the MD5 hash. MD5 is an example of a hashing method. For example, the MD5 hash of "hello" (without the quotes) is "5d41402abc4b2a76b97
5 min read
What is the difference between Hashing and Hash Tables?
What is Hashing? Hashing refers to the process of generating a fixed-size output from an input of variable size using the mathematical formulas known as hash functions. This technique determines an index or location for the storage of an item in a data structure. It might not be strictly related to key-value pairs only if you are manipulating the d
2 min read
String hashing using Polynomial rolling hash function
Hash FunctionA Hash function is a function that maps any kind of data of arbitrary size to fixed-size values. The values returned by the function are called Hash Values or digests. There are many popular Hash Functions such as DJBX33A, MD5, and SHA-256. This post will discuss the key features, implementation, advantages and drawbacks of the Polynom
27 min read
What are Hash Functions and How to choose a good Hash Function?
Prerequisite: Hashing | Set 1 (Introduction) What is a Hash Function? A function that converts a given big phone number to a small practical integer value. The mapped integer value is used as an index in the hash table. In simple terms, a hash function maps a big number or string to a small integer that can be used as the index in the hash table. W
5 min read
Hash Functions and Types of Hash functions
Hash functions are a fundamental concept in computer science and play a crucial role in various applications such as data storage, retrieval, and cryptography. In data structures and algorithms (DSA), hash functions are primarily used in hash tables, which are essential for efficient data management. This article delves into the intricacies of hash
4 min read
Difference between Instance Variable and Class Variable
Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values. They are tied to a particular object instance of the class, therefore, the contents of an instance variable are totally independent of one object instance to
2 min read
Difference between Instance Variable and Local Variable
A variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution.A variable is only a name given to a memory location. All the operations are done on the variable effects of a memory location.In Java, all the variables must be declared before use.In
3 min read
Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
What is the Variable stack size ?
What variable stack size is and how does it affect computer networks? A variable stack depth (VSD) means that the maximum number of frames the system can store in its transmit buffer changes dynamically. When the number of free buffers nears exhaustion, the VSD decreases, freeing space in the buffer pool by discarding buffers as it receives them an
4 min read
Why can't a const variable be used to define an Array's initial size in C?
What is an array? An array is a collection of items of the same data type stored at contiguous memory locations. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array). The base value is index
3 min read