[go: up one dir, main page]

0% found this document useful (0 votes)
23 views22 pages

NS & C - Journal-2

Uploaded by

shaikh.juveria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views22 pages

NS & C - Journal-2

Uploaded by

shaikh.juveria
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Name - Shaikh Juveria Shafi Ahmed Roll No.

- SY MSc CS 05

Practical No. - 01
Aim - Implement a Basic Encryption and Decryption Process for Plaintext
Data. Use Cryptographic Libraries (e.g., OpenSSL, Python
Cryptography Library or a Similar Encryption Toolkit) to Encrypt and
Decrypt a Given Plaintext Message.
__________________________________________________________________

Theory:

Encryption is the process of converting plaintext data into a coded format, known as ciphertext,
to prevent unauthorized access. This transformation uses an algorithm and a key, ensuring that
only those with the correct key can decrypt and access the original data. Decryption is the
reverse process, converting ciphertext back into its original plaintext format using a key.
Encryption and decryption are fundamental to data security, ensuring confidentiality and
protecting information during transmission or storage. Symmetric encryption uses the same key
for both processes, while asymmetric encryption uses a pair of keys—a public key for encryption
and a private key for decryption.

Source Code: fernet.py

from cryptography.fernet import Fernet

# Generate a key for encryption and decryption


def generate_key():
return Fernet.generate_key()

# Encrypt a message
def encrypt_message(message, key):
fernet = Fernet(key)
encrypted_message = fernet.encrypt(message.encode())
return encrypted_message

# Decrypt a message
def decrypt_message(encrypted_message, key):
fernet = Fernet(key)
decrypted_message = fernet.decrypt(encrypted_message).decode()
return decrypted_message

# Example usage:
key = generate_key()
print("Encryption Key: ", key) # Print the key as bytes
message = input("Enter the plaintext: ")
encrypted_message = encrypt_message(message, key)

Subject - Network Security and Cryptography 1


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 01
Aim - Implement a Basic Encryption and Decryption Process for Plaintext
Data. Use Cryptographic Libraries (e.g., OpenSSL, Python
Cryptography Library or a Similar Encryption Toolkit) to Encrypt and
Decrypt a Given Plaintext Message.
__________________________________________________________________

print("Encrypted: ", encrypted_message)


decrypted_message = decrypt_message(encrypted_message, key)
print("Decrypted: ", decrypted_message)

Output: fernet.py

Subject - Network Security and Cryptography 2


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 02
Aim - Develop Encryption and Decryption Routines for DES Algorithm.
Tools/Technologies: Cryptographic Libraries, Programming Languages
like Python or Java.
__________________________________________________________________

Theory:

The Data Encryption Standard (DES) is a symmetric-key block cipher that was widely used for
data encryption. Developed in the 1970s by IBM and adopted by the U.S. National Institute of
Standards and Technology (NIST) in 1977, DES encrypts data in 64-bit blocks using a 56-bit
key. DES operates through a series of permutations and substitutions, creating complex
encryption transformations. Although it was considered secure for many years, advancements in
computing power have made DES vulnerable to brute-force attacks. As a result, DES has been
largely replaced by more secure algorithms like AES (Advanced Encryption Standard) in modern
applications.

Source Code: des.py

from Crypto.Cipher import DES


from Crypto.Util.Padding import pad, unpad
import base64

# Function to encrypt plaintext using DES


def des_encrypt(plaintext, key):
# Convert the key and plaintext to bytes
key = key.encode('utf-8')
plaintext = plaintext.encode('utf-8')

# Create a new DES cipher in ECB mode


cipher = DES.new(key, DES.MODE_ECB)

# Pad the plaintext to be a multiple of 8 bytes


padded_text = pad(plaintext, DES.block_size)

# Encrypt the padded plaintext


encrypted_text = cipher.encrypt(padded_text)

# Convert encrypted bytes to base64 to get a printable string


encrypted_text_base64 = base64.b64encode(encrypted_text).decode('utf-8')

return encrypted_text_base64

# Function to decrypt ciphertext using DES

Subject - Network Security and Cryptography 3


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 02
Aim - Develop Encryption and Decryption Routines for DES Algorithm.
Tools/Technologies: Cryptographic Libraries, Programming Languages
like Python or Java.
__________________________________________________________________

def des_decrypt(ciphertext_base64, key):


# Convert the key and ciphertext to bytes
key = key.encode('utf-8')
ciphertext = base64.b64decode(ciphertext_base64)

# Create a new DES cipher in ECB mode


cipher = DES.new(key, DES.MODE_ECB)

# Decrypt the ciphertext


decrypted_padded_text = cipher.decrypt(ciphertext)

# Unpad the decrypted plaintext


decrypted_text = unpad(decrypted_padded_text, DES.block_size).decode('utf-8')

return decrypted_text

# Main program with user input and menu options


def main():
while True:
print("\nChoose an option:")
print("1. Encrypt")
print("2. Decrypt")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == '1':
plaintext = input("Enter the plaintext to encrypt: ")
key = input("Enter an 8-character key: ")
if len(key) != 8:
print("Key must be exactly 8 characters long.")
continue
ciphertext = des_encrypt(plaintext, key)
print(f"Encrypted Text: {ciphertext}")

elif choice == '2':


ciphertext = input("Enter the base64-encoded ciphertext to decrypt: ")
key = input("Enter the 8-character key used for encryption: ")
if len(key) != 8:

Subject - Network Security and Cryptography 4


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 02
Aim - Develop Encryption and Decryption Routines for DES Algorithm.
Tools/Technologies: Cryptographic Libraries, Programming Languages
like Python or Java.
__________________________________________________________________

print("Key must be exactly 8 characters long.")


continue
try:
decrypted_text = des_decrypt(ciphertext, key)
print(f"Decrypted Text: {decrypted_text}")
except (ValueError, KeyError):
print("Decryption failed. Check your key and ciphertext.")

elif choice == '3':


print("Exiting the program.")
break

else:
print("Invalid choice. Please try again.")

# Run the main function


if __name__ == "__main__":
main()

Output: des.py

Subject - Network Security and Cryptography 5


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 03
Aim - Develop the Elgamal Encryption System, Including Key Generation,
Encryption and Decryption Processes. Tools/Technologies:
Cryptographic Libraries, Python or Specialized Encryption Software.
__________________________________________________________________

Theory:

The ElGamal encryption system is a public-key cryptosystem based on the Diffie-Hellman key
exchange. Developed by Taher ElGamal in 1984, it uses asymmetric cryptography to encrypt and
decrypt messages. The system involves selecting a large prime number ‘p’ and a generator ‘g’ of
the multiplicative group modulo ‘p’. Each user has a private key ‘x’ and a public key ‘y’, where
y = gx mod p. Encryption involves choosing a random integer ‘k’ to generate a pair of ciphertext
values. Decryption requires the private key to recover the original message. ElGamal is known
for its security based on the hardness of the discrete logarithm problem.

Source Code: elgamal.py

import random

def generate_keys():
# Step 1: Enter a large prime number p
p = int(input("Enter a large prime number p: "))

# Step 2: Choose a generator g of the multiplicative group Z_p^*


g = int(input("Enter a generator g: "))

# Step 3: Select a private key x


x = random.randint(1, p-2) # 1 <= x < p-1

# Step 4: Compute the public key y


y = pow(g, x, p)

# Public key (p, g, y) and private key (x)


public_key = (p, g, y)
private_key = x

return public_key, private_key

def encrypt(public_key, message):


p, g, y = public_key

# Step 1: Convert the message to an integer (for simplicity, assuming message is an integer)
m = message

Subject - Network Security and Cryptography 6


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 03
Aim - Develop the Elgamal Encryption System, Including Key Generation,
Encryption and Decryption Processes. Tools/Technologies:
Cryptographic Libraries, Python or Specialized Encryption Software.
__________________________________________________________________

# Step 2: Choose a random integer k


k = random.randint(1, p-2) # 1 <= k < p-1

# Step 3: Compute ciphertext components


c1 = pow(g, k, p)
c2 = (m * pow(y, k, p)) % p

# Return the ciphertext as a tuple (c1, c2)


return (c1, c2)

def decrypt(ciphertext, public_key, private_key):


p, g, y = public_key
x = private_key
c1, c2 = ciphertext

# Step 1: Compute the plaintext message


s = pow(c1, x, p)
plaintext = (c2 * pow(s, p-2, p)) % p

# Return the plaintext (assuming it's an integer for simplicity)


return plaintext

# Example usage
public_key, private_key = generate_keys()
print("Public Key:", public_key)
print("Private Key:", private_key)

message = 9
print("Original Message:", message)

ciphertext = encrypt(public_key, message)


print("Ciphertext:", ciphertext)

decrypted_message = decrypt(ciphertext, public_key, private_key)


print("Decrypted Message:", decrypted_message)

Subject - Network Security and Cryptography 7


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 03
Aim - Develop the Elgamal Encryption System, Including Key Generation,
Encryption and Decryption Processes. Tools/Technologies:
Cryptographic Libraries, Python or Specialized Encryption Software.
__________________________________________________________________

Output: elgamal.py

Subject - Network Security and Cryptography 8


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 04
Aim - Implement the Playfair Cipher Algorithm and Develop Encryption and
Decryption Routines, Including the 5x5 Matrix and Matrix Indexes.
Tools/Technologies: Programming Languages, such as Python or Java
for algorithm Implementation.
__________________________________________________________________

Theory:

The Playfair cipher is a digraph substitution cipher devised by Charles Wheatstone in 1854 and
popularized by Sir Frank Playfair. It encrypts pairs of letters rather than single letters. The
algorithm uses a 5x5 matrix of letters, constructed from a keyword, with the remaining letters of
the alphabet (excluding duplicates and usually combining 'I' and 'J' into one) filling the rest. To
encrypt, each pair of plaintext letters is located in the matrix and substituted based on their
positions: if they’re in the same row or column, they’re replaced by letters in the same row or
column but shifted. If not, they form a rectangle, and the opposite corners are swapped. This
method enhances security compared to simple substitution ciphers.

Source Code: playfair.py

import numpy as np

# Function to prepare the Playfair matrix based on a keyword


def create_playfair_matrix(keyword):
keyword = keyword.upper().replace('J', 'I')
seen = set()
matrix = []

# Add keyword to matrix and remove duplicates


for char in keyword:
if char not in seen and char.isalpha():
seen.add(char)
matrix.append(char)

# Add remaining letters of the alphabet


for char in 'ABCDEFGHIKLMNOPQRSTUVWXYZ': # 'J' is omitted (replaced with 'I')
if char not in seen:
matrix.append(char)

# Reshape the list into a 5x5 matrix


matrix = np.array(matrix).reshape(5, 5)

return matrix

Subject - Network Security and Cryptography 9


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 04
Aim - Implement the Playfair Cipher Algorithm and Develop Encryption and
Decryption Routines, Including the 5x5 Matrix and Matrix Indexes.
Tools/Technologies: Programming Languages, such as Python or Java
for algorithm Implementation.
__________________________________________________________________

# Function to find the position of a letter in the matrix


def find_position(matrix, char):
for i, row in enumerate(matrix):
for j, matrix_char in enumerate(row):
if matrix_char == char:
return i, j
return None

# Function to format the plaintext


def format_text(plaintext):
plaintext = plaintext.upper().replace('J', 'I')
formatted_text = ""

# Remove non-alphabetic characters


plaintext = ''.join([char for char in plaintext if char.isalpha()])

# Add 'X' between repeating characters and at the end if odd length
i=0
while i < len(plaintext):
formatted_text += plaintext[i]
if i + 1 < len(plaintext) and plaintext[i] == plaintext[i + 1]:
formatted_text += 'X'
elif i + 1 < len(plaintext):
formatted_text += plaintext[i + 1]
i += 1
i += 1

if len(formatted_text) % 2 != 0:
formatted_text += 'X'

return formatted_text

# Function to encrypt the plaintext using Playfair cipher


def playfair_encrypt(plaintext, matrix):
plaintext = format_text(plaintext)
ciphertext = ""

Subject - Network Security and Cryptography 10


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 04
Aim - Implement the Playfair Cipher Algorithm and Develop Encryption and
Decryption Routines, Including the 5x5 Matrix and Matrix Indexes.
Tools/Technologies: Programming Languages, such as Python or Java
for algorithm Implementation.
__________________________________________________________________

for i in range(0, len(plaintext), 2):


char1, char2 = plaintext[i], plaintext[i + 1]
row1, col1 = find_position(matrix, char1)
row2, col2 = find_position(matrix, char2)

if row1 == row2:
# Same row, shift right
ciphertext += matrix[row1][(col1 + 1) % 5] + matrix[row2][(col2 + 1) % 5]
elif col1 == col2:
# Same column, shift down
ciphertext += matrix[(row1 + 1) % 5][col1] + matrix[(row2 + 1) % 5][col2]
else:
# Rectangle swap
ciphertext += matrix[row1][col2] + matrix[row2][col1]

return ciphertext

# Function to decrypt the ciphertext using Playfair cipher


def playfair_decrypt(ciphertext, matrix):
plaintext = ""

for i in range(0, len(ciphertext), 2):


char1, char2 = ciphertext[i], ciphertext[i + 1]
row1, col1 = find_position(matrix, char1)
row2, col2 = find_position(matrix, char2)

if row1 == row2:
# Same row, shift left
plaintext += matrix[row1][(col1 - 1) % 5] + matrix[row2][(col2 - 1) % 5]
elif col1 == col2:
# Same column, shift up
plaintext += matrix[(row1 - 1) % 5][col1] + matrix[(row2 - 1) % 5][col2]
else:
# Rectangle swap
plaintext += matrix[row1][col2] + matrix[row2][col1]

return plaintext

Subject - Network Security and Cryptography 11


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 04
Aim - Implement the Playfair Cipher Algorithm and Develop Encryption and
Decryption Routines, Including the 5x5 Matrix and Matrix Indexes.
Tools/Technologies: Programming Languages, such as Python or Java
for algorithm Implementation.
__________________________________________________________________

# Main program with user input and menu options


def main():
keyword = input("Enter the keyword for the Playfair Cipher: ")
matrix = create_playfair_matrix(keyword)

while True:
print("\nChoose an option:")
print("1. Encrypt")
print("2. Decrypt")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ")

if choice == '1':
plaintext = input("Enter the plaintext to encrypt: ")
ciphertext = playfair_encrypt(plaintext, matrix)
print(f"Ciphertext: {ciphertext}")

elif choice == '2':


ciphertext = input("Enter the ciphertext to decrypt: ")
decrypted_text = playfair_decrypt(ciphertext, matrix)
print(f"Decrypted Text: {decrypted_text}")

elif choice == '3':


print("Exiting the program.")
break

else:
print("Invalid choice. Please try again.")

# Run the main function


if __name__ == "__main__":
main()

Subject - Network Security and Cryptography 12


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 04
Aim - Implement the Playfair Cipher Algorithm and Develop Encryption and
Decryption Routines, Including the 5x5 Matrix and Matrix Indexes.
Tools/Technologies: Programming Languages, such as Python or Java
for algorithm Implementation.
__________________________________________________________________

Output: playfair.py

Subject - Network Security and Cryptography 13


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 05
Aim - Implement Cryptographic Algorithm Diffie-Hellman Key Exchange.
Tools/Technologies: Cryptographic Libraries, Programming Languages
and Hashing Utilities.
__________________________________________________________________

Theory:

The Diffie-Hellman key exchange is a cryptographic protocol allowing two parties to securely
share a secret key over an insecure communication channel. Introduced by Whitfield Diffie and
Martin Hellman in 1976, it leverages modular arithmetic and the difficulty of solving discrete
logarithms. Both parties agree on a large prime number ‘p’ and a base ‘g’. Each party generates a
private key and computes a public key based on ‘g’ and their private key. They exchange public
keys and each computes the shared secret using their private key and the other party’s public key.
The shared secret is identical for both parties and can be used for symmetric encryption.

Source Code: deffie.py

import random

def generate_private_key(p):
"""Generate a private key."""
return random.randint(2, p-2)

def generate_public_key(p, g, private_key):


"""Generate a public key."""
return pow(g, private_key, p)

def compute_shared_secret(public_key, private_key, p):


"""Compute the shared secret key."""
return pow(public_key, private_key, p)

def main():
# Step 1: Select a large prime number p and a generator g
p = int(input("Enter a large prime number p: "))
g = int(input("Enter a generator g: "))

# Each party generates their private and public keys


print("\nParty A:")
private_key_a = generate_private_key(p)
public_key_a = generate_public_key(p, g, private_key_a)
print(f"Private Key A: {private_key_a}")
print(f"Public Key A: {public_key_a}")

Subject - Network Security and Cryptography 14


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 05
Aim - Implement Cryptographic Algorithm Diffie-Hellman Key Exchange.
Tools/Technologies: Cryptographic Libraries, Programming Languages
and Hashing Utilities.
__________________________________________________________________

print("\nParty B:")
private_key_b = generate_private_key(p)
public_key_b = generate_public_key(p, g, private_key_b)
print(f"Private Key B: {private_key_b}")
print(f"Public Key B: {public_key_b}")

# Each party computes the shared secret


shared_secret_a = compute_shared_secret(public_key_b, private_key_a, p)
shared_secret_b = compute_shared_secret(public_key_a, private_key_b, p)

print("\nShared Secret Computation:")


print(f"Party A's Computed Shared Secret: {shared_secret_a}")
print(f"Party B's Computed Shared Secret: {shared_secret_b}")

# Verify that both parties have the same shared secret


if shared_secret_a == shared_secret_b:
print("The shared secret is successfully established.")
else:
print("Error: The shared secrets do not match.")

# Run the main function


if __name__ == "__main__":
main()

Output: deffie.py

Subject - Network Security and Cryptography 15


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 06
Aim - Develop Encryption and Decryption Routine for RSA Algorithm.
Tools/Technologies: Cryptographic Libraries, Programming Languages
like Python or Java.
__________________________________________________________________

Theory:

RSA (Rivest-Shamir-Adleman) is a widely used public-key cryptographic algorithm developed


in 1977 by Ron Rivest, Adi Shamir, and Leonard Adleman. It is based on the mathematical
difficulty of factoring large composite numbers. RSA involves generating two large prime
numbers ‘p’ and ‘q’, and computing their product n = p x q. The public key consists of ‘n’ and an
exponent ‘e’, while the private key includes ‘n’ and a private exponent ‘d’, derived from ‘e’ and
the totient function of ‘n’. RSA enables secure encryption and digital signatures by utilizing
modular exponentiation.

Source Code: rsa.py

import random
from sympy import isprime, mod_inverse
import base64

def generate_prime(bits=8):
"""Generate a random prime number of specified bit length."""
while True:
num = random.getrandbits(bits)
if isprime(num):
return num

def generate_keys():
"""Generate RSA public and private keys."""
p = generate_prime()
q = generate_prime()

n=p*q
phi_n = (p - 1) * (q - 1)

e = 65537 # Common choice for e

# Ensure e is coprime with phi(n) and has an inverse modulo phi(n)


d = mod_inverse(e, phi_n)

# Public key is (n, e) and private key is (n, d)


public_key = (n, e)

Subject - Network Security and Cryptography 16


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 06
Aim - Develop Encryption and Decryption Routine for RSA Algorithm.
Tools/Technologies: Cryptographic Libraries, Programming Languages
like Python or Java.
__________________________________________________________________

private_key = (n, d)

return public_key, private_key

def encrypt(public_key, message):


"""Encrypt a message using RSA public key."""
n, e = public_key

# Convert the message to bytes and then to an integer


message_bytes = message.encode('utf-8')
m = int.from_bytes(message_bytes, byteorder='big')

# Encrypt the message


c = pow(m, e, n)

return c

def decrypt(private_key, ciphertext):


"""Decrypt a ciphertext using RSA private key."""
n, d = private_key

# Decrypt the ciphertext


m = pow(ciphertext, d, n)

# Convert the integer back to bytes and then decode to a string


message_bytes = m.to_bytes((m.bit_length() + 7) // 8, byteorder='big')
message = message_bytes.decode('utf-8', errors='ignore')

return message

# Example usage
public_key, private_key = generate_keys()
print("Public Key:", public_key)
print("Private Key:", private_key)

message = "Kill the PM"


print("Original Message:", message)

ciphertext = encrypt(public_key, message)

Subject - Network Security and Cryptography 17


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 06
Aim - Develop Encryption and Decryption Routine for RSA Algorithm.
Tools/Technologies: Cryptographic Libraries, Programming Languages
like Python or Java.
__________________________________________________________________

print("Ciphertext:", ciphertext)

decrypted_message = decrypt(private_key, ciphertext)


print("Decrypted Message:", decrypted_message)

Output: rsa.py

Subject - Network Security and Cryptography 18


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 07
Aim - Implement Cryptographic Algorithm MD5. Tools/Technologies:
Cryptographic Libraries, Programming Languages and Hashing
Utilities.
__________________________________________________________________

Theory:

MD5 (Message Digest Algorithm 5) is a widely used cryptographic hash function that produces a
128-bit hash value from input data. Designed by Ronald Rivest in 1991, MD5 is commonly used
for data integrity verification and checksums. It processes input data in 512-bit blocks, resulting
in a fixed-size 128-bit hash value. Despite its popularity, MD5 is now considered
cryptographically broken and unsuitable for security purposes due to vulnerabilities such as
susceptibility to collision attacks, where different inputs produce the same hash. As a result,
MD5 is largely replaced by more secure hashing algorithms like SHA-256 in modern
applications.

Source Code: md5.py

import hashlib

def md5_hash(message):
"""Compute the MD5 hash of a given message."""
# Create an MD5 hash object
md5 = hashlib.md5()

# Update the hash object with the bytes of the message


md5.update(message.encode('utf-8'))

# Get the hexadecimal representation of the digest


hash_value = md5.hexdigest()

return hash_value

# Example usage
message = "The weather is gloomy"
print("Original Message:", message)

hash_value = md5_hash(message)
print("MD5 Hash:", hash_value)

Subject - Network Security and Cryptography 19


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 07
Aim - Implement Cryptographic Algorithm MD5. Tools/Technologies:
Cryptographic Libraries, Programming Languages and Hashing
Utilities.
__________________________________________________________________

Output: md5.py

Subject - Network Security and Cryptography 20


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 08
Aim - Implement Cryptographic Algorithm SHA-1. Tools/Technologies:
Cryptographic Libraries, Programming Languages and Hashing
Utilities.
__________________________________________________________________

Theory:

SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function designed by the NSA and
published by NIST in 1993. It produces a 160-bit hash value from input data, typically
represented as a 40-digit hexadecimal number. SHA-1 processes data in 512-bit blocks,
generating a fixed-size 160-bit hash. Initially used for data integrity and digital signatures,
SHA-1 is now considered weak due to vulnerabilities, including susceptibility to collision attacks
where different inputs generate the same hash. As a result, SHA-1 has been deprecated in favour
of more secure algorithms like SHA-256, which provide stronger cryptographic security.

Source Code: sha1.py

import hashlib

def sha1_hash(message):
"""Compute the SHA-1 hash of a given message."""
# Create a SHA-1 hash object
sha1 = hashlib.sha1()

# Update the hash object with the bytes of the message


sha1.update(message.encode('utf-8'))

# Get the hexadecimal representation of the digest


hash_value = sha1.hexdigest()

return hash_value

# Example usage
message = "Sunshine and Moonlight"
print("Original Message:", message)

hash_value = sha1_hash(message)
print("SHA-1 Hash:", hash_value)

Subject - Network Security and Cryptography 21


Name - Shaikh Juveria Shafi Ahmed Roll No. - SY MSc CS 05

Practical No. - 08
Aim - Implement Cryptographic Algorithm SHA-1. Tools/Technologies:
Cryptographic Libraries, Programming Languages and Hashing
Utilities.
__________________________________________________________________

Output: sha1.py

Subject - Network Security and Cryptography 22

You might also like