import hashlib
def md5_hash(message):
md5 = hashlib.md5()
md5.update(message.encode())
return md5.hexdigest()
message = "Hello, this is a test message for MD5 hashing!"
hashed_message = md5_hash(message)
print(f"Original Message: {message}")
print(f"MD5 Hash: {hashed_message}")
import struct
import math
# Left rotation function
def left_rotate(x, amount):
x &= 0xFFFFFFFF
return ((x << amount) | (x >> (32 - amount))) & 0xFFFFFFFF
# Main MD5 function
def md5(message):
# s specifies the per-round shift amounts
s = [7, 12, 17, 22] * 4 + \
[5, 9, 14, 20] * 4 + \
[4, 11, 16, 23] * 4 + \
[6, 10, 15, 21] * 4
# Use binary integer part of the sines of integers (in radians) as constants
K = [int(abs(math.sin(i + 1)) * 2**32) & 0xFFFFFFFF for i in range(64)]
# Initialize variables
a0 = 0x67452301 # A
b0 = 0xEFCDAB89 # B
c0 = 0x98BADCFE # C
d0 = 0x10325476 # D
# Pre-processing
original_len_in_bits = (8 * len(message)) & 0xffffffffffffffff
message += b'\x80'
while len(message) % 64 != 56:
message += b'\x00'
message += struct.pack('<Q', original_len_in_bits)
# Process the message in 512-bit (64-byte) chunks
for chunk_offset in range(0, len(message), 64):
chunk = message[chunk_offset:chunk_offset+64]
M = list(struct.unpack('<16I', chunk))
A, B, C, D = a0, b0, c0, d0
for i in range(64):
if 0 <= i <= 15:
F = (B & C) | (~B & D)
g = i
elif 16 <= i <= 31:
F = (D & B) | (~D & C)
g = (5*i + 1) % 16
elif 32 <= i <= 47:
F = B ^ C ^ D
g = (3*i + 5) % 16
elif 48 <= i <= 63:
F = C ^ (B | ~D)
g = (7*i) % 16
F = (F + A + K[i] + M[g]) & 0xFFFFFFFF
A, D, C, B = D, C, B, (B + left_rotate(F, s[i])) & 0xFFFFFFFF
# Add this chunk's hash to result so far:
a0 = (a0 + A) & 0xFFFFFFFF
b0 = (b0 + B) & 0xFFFFFFFF
c0 = (c0 + C) & 0xFFFFFFFF
d0 = (d0 + D) & 0xFFFFFFFF
# Return the final MD5 digest as a 32-digit hexadecimal string
return ''.join(f'{x:02x}' for x in struct.pack('<4I', a0, b0, c0, d0))
# Example usage
if __name__ == '__main__':
test1 = b"hello world"
test2 = b"GeeksForGeeks"
print("MD5 of 'hello world':", md5(test1))
print("MD5 of 'GeeksForGeeks':", md5(test2))