CNS Practical-12

import hashlib

def sha1_hash(message):
    sha1 = hashlib.sha1()
    sha1.update(message.encode())   
    return sha1.hexdigest()

message = "Hello, this is a test message for SHA-1 hashing!"
hashed_message = sha1_hash(message)

print(f"Original Message: {message}")
print(f"SHA-1 Hash: {hashed_message}")
def left_rotate(n, b):
    return ((n << b) | (n >> (32 - b))) & 0xffffffff

def sha1(message):
    # Initialize variables
    h0 = 0x67452301
    h1 = 0xEFCDAB89
    h2 = 0x98BADCFE
    h3 = 0x10325476
    h4 = 0xC3D2E1F0

    # Pre-processing
    message = bytearray(message, 'utf-8')
    original_byte_len = len(message)
    original_bit_len = original_byte_len * 8

    message.append(0x80)
    while (len(message) * 8) % 512 != 448:
        message.append(0)

    message += original_bit_len.to_bytes(8, 'big')

    # Process the message in 512-bit chunks
    for i in range(0, len(message), 64):
        w = [0] * 80
        chunk = message[i:i + 64]
        for j in range(16):
            w[j] = int.from_bytes(chunk[j*4:(j*4)+4], 'big')
        for j in range(16, 80):
            w[j] = left_rotate(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1)

        a, b, c, d, e = h0, h1, h2, h3, h4

        for i in range(80):
            if 0 <= i <= 19:
                f = (b & c) | ((~b) & d)
                k = 0x5A827999
            elif 20 <= i <= 39:
                f = b ^ c ^ d
                k = 0x6ED9EBA1
            elif 40 <= i <= 59:
                f = (b & c) | (b & d) | (c & d)
                k = 0x8F1BBCDC
            else:
                f = b ^ c ^ d
                k = 0xCA62C1D6

            temp = (left_rotate(a, 5) + f + e + k + w[i]) & 0xffffffff
            e = d
            d = c
            c = left_rotate(b, 30)
            b = a
            a = temp

        h0 = (h0 + a) & 0xffffffff
        h1 = (h1 + b) & 0xffffffff
        h2 = (h2 + c) & 0xffffffff
        h3 = (h3 + d) & 0xffffffff
        h4 = (h4 + e) & 0xffffffff

    return ''.join(f'{x:08x}' for x in [h0, h1, h2, h3, h4])


# Test example
s1 = "Prince"
s2 = "hello world"

print(f"{s1} : {sha1(s1)}")
print(f"{s2} : {sha1(s2)}")

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!
Scroll to Top