You are on page 1of 3

Name: Farhan Ali

Sec: 7A
Merkle Damgard Construction
Information Security
Roll: 20p-0019

The Merkle-Damgård construction is a method used to build a cryptographic hash


function by iteratively processing blocks of data through a compression function.
It's widely used in constructing many popular hash functions, including MD5, SHA-
1, and SHA-256. The Merkle-Damgård construction operates on a fixed-size block
of data and produces a fixed-size hash output. The key idea is to take an input
message, break it into blocks, and iteratively process these blocks while updating
a state (called the chaining variable) to produce the final hash.

Here's a high-level description of the Merkle-Damgård construction:

1. **Padding**: If the message length is not a multiple of the block size, padding
is applied to make it fit.

2. **Divide into Blocks**: The padded message is divided into equal-sized blocks.

3. **Initialization**: An initial value or constant is set as the initial chaining


variable.
4. **Compression Function**: A compression function takes the current chaining
variable and the current message block as inputs, and updates the chaining
variable. The compression function operates on a block of data and produces a
fixed-size output.

5. **Iterate**: The compression function is applied iteratively to each message


block, updating the chaining variable with each step.

6. **Finalization**: The final value of the chaining variable is the hash output.

Source Code:
import hashlib
# Simulated compression function (a simple XOR operation)
def custom_compression(chaining_var, block):
# Perform a bitwise XOR between chaining_var and block
return chaining_var ^ block

# The Merkle-Damgård construction


def merkle_damgard(message, block_size, compression_function):
# Padding
padded_message = message + b'\x80'
while len(padded_message) % block_size != 0:
padded_message += b'\x00'

# Divide into blocks


blocks = [int.from_bytes(padded_message[i:i+block_size], 'big') for i in range(0,
len(padded_message), block_size)]

# Initialization
chaining_var = 0

# Iterate through blocks


for block in blocks:
chaining_var = compression_function(chaining_var, block)

# Finalization
return chaining_var

# Example usage
message = b"Hello, World!"
block_size = 4 # In bytes
hash_output = merkle_damgard(message, block_size, custom_compression)
print(f"Hash output: {hash_output:x}")
```

You might also like