Cryptography Lab
Cryptography Lab
PROGRAMS TO BE PRACTICED
Part - A
1. Write a Java program to perform encryption and
decryption using the following algorithms
a) Ceaser Cipher 5
b) Substitution Cipher
c) Hill Cipher
2 Write a program to implement the DES algorithm logic 8
3. Write a program to implement RSA Algorithm 11
4. Implement the Diffie-Hellman Key Exchange
mechanism using HTML and JavaScript. Consider the
15
end user as one of the parties (Alice) and the JavaScript
application as other party (bob)
5. Calculate the message digest of a text using the SHA-1
19
algorithm
Part - B
A) CEASER CIPHER
AIM: Python program to perform encryption and Decryption of the Caesar
cipher algorithm.
SOURCE CODE:
def caesar_cipher(text, shift):
result = " "
# Loop through each character in the text
for char in text:
if char.isalpha(): # Check if the character is a letter
shift_amount = shift % 26 # Ensure shift is within alphabet range
# Determine the ASCII offset based on uppercase or lowercase letter
ascii_offset = 65 if char.isupper() else 97
# Calculate the new character's position in the alphabet
new_char = chr((ord(char) - ascii_offset + shift_amount) % 26 +
ascii_offset)
result += new_char
else
result += char
return result
plaintext = input("Enter the plain text")
shift = int(input("Entre the number of shifts"))
ciphertext = caesar_cipher(plaintext, shift)
print("Plaintext for caesar:", plaintext)
print("Shift:", shift)
print("Ciphertext from caesar:", ciphertext)
originaltext = caesar_cipher(ciphertext, -shift)
print("Originaltext for caesar:", originaltext)
OUTPUT:
RESULT:
We have successfully executed the source code for Caeser cipher and the output
is obtained.
B) SUBSTITUTION CIPHER
SOURCE CODE:
import string
def generate_substitution_key():
# Generates a random substitution key by shuffling the alphabet
alphabet = list(string.ascii_lowercase)
shuffled_alphabet = alphabet[:]
import random
random.shuffle(shuffled_alphabet)
return dict(zip(alphabet, shuffled_alphabet))
# Example usage
plaintext = input("Enter the plain text")
ciphertext = encrypt(plaintext, substitution_key)
print("Plaintext:", plaintext)
print("Ciphertext:", ciphertext)
OUTPUT:
RESULT
We have successfully executed the source code for Substitution cipher and the
output is obtained
C) HILL CIPHER
SOURCE CODE:
import numpy as np
def getKeyMatrix(key):
k=0
for i in range(3):
for j in range(3):
keyMatrix[i][j] = ord(key[k]) - 65 # Convert to range 0-25
k += 1
def adjugate(matrix):
"""Compute the adjugate of a 3x3 matrix."""
a, b, c, d, e, f, g, h, i = matrix.flatten()
adjugate_matrix = np.array([
[e*i - f*h, c*h - b*i, b*f - c*e],
[f*g - d*i, a*i - c*g, c*d - a*f],
[d*h - e*g, b*g - a*h, a*e - b*d]
])
return adjugate_matrix
return inv_matrix
def encrypt(messageVector):
for i in range(3):
for j in range(1):
cipherMatrix[i][j] = 0
for x in range(3):
cipherMatrix[i][j] += (messageVector[x][j] * keyMatrix[i][x])
cipherMatrix[i][j] = cipherMatrix[i][j] % 26
return decryptedMatrix
print("Key Matrix:")
for row in keyMatrix:
print(row)
for i in range(3):
messageVector[i][0] = ord(message[i]) - 65 # Convert message to
matrix
print("Message Matrix:")
for row in messageVector:
print(row)
encrypt(messageVector)
print("Cipher Matrix:")
for row in cipherMatrix:
print(row)
CipherText = []
for i in range(3):
CipherText.append(chr(cipherMatrix[i][0] + 65)) # Convert back to
letters
print("Ciphertext: ", "".join(CipherText))
print("Decrypted Matrix:")
for row in decryptedMatrix:
print(row)
DecryptedText = []
for i in range(3):
DecryptedText.append(chr(decryptedMatrix[i][0] + 65)) # Convert
back to letters
print("Decrypted Text: ", "".join(DecryptedText))
# Driver Code
def main():
message = "MOR" # Example message
key = "RVCRSCFVT" # Example key
HillCipher(message, key)
if __name__ == "__main__":
main()
OUTPUT:
RESULT:
We have successfully executed the source code for Hill cipher and the output is
obtained
PROGRAM 2
DATA ENCRYPTION STANDARDS
SOURCE CODE:
!pip install pycryptodome
return decrypted_data.decode('utf-8')
# Example usage
if __name__ == "__main__":
# Sample key and data
key = '12345678' # Key must be 8 bytes for DES
data = 'naveen'
# Encrypt data
iv, encrypted_data = encrypt_des(key, data)
print("Encrypted Data:", encrypted_data)
print("IV:", iv)
# Decrypt data
decrypted_data = decrypt_des(key, iv, encrypted_data)
print("Decrypted Data:", decrypted_data)
OUTPUT:
RESULT:
We have successfully executed the DES source code and the output is obtained.
PROGRAM 3
RSA
SOURCE CODE:
from math import gcd
OUTPUT:
RESULT:
We have successfully executed the source code for RSA and the output is
obtained.
PROGRAM 4
DIFFIE-HELLMAN KEY EXCHANGE
SOURCE CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diffie-Hellman Key Exchange</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
input {
padding: 10px;
margin: 10px;
width: 300px;
font-size: 16px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
.result {
margin-top: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Diffie-Hellman Key Exchange</h1>
<p>Enter your private key (Alice's private key)</p>
<input type="number" id="alicePrivateKey" placeholder="Enter Alice's
private key">
<button onclick="performKeyExchange()">Compute Shared Secret</button>
<script>
// Parameters agreed upon by Alice and Bob
const p = 23; // Prime number
const g = 5; // Primitive root mod p
function performKeyExchange() {
// Get Alice's private key from the input field
const alicePrivateKey =
parseInt(document.getElementById("alicePrivateKey").value);
RESULT:
We have successfully executed the source code for Diffie-Hellman Key
Exchange and the output is obtained.
PROGRAM 5
SECURED HASH FUNCTION
AIM: Write a program in python to calculate the message digest of a text using
the SHA-1 algorithm
SOURCE CODE:
import hashlib
import ipywidgets as widgets
from IPython.display import display
with output_widget:
print(f"Step 1: Input string converted to bytes:
{input_bytes.hex()}")
with output_widget:
print(f"Step 2: {hash_name} object initialized")
hash_object.update(input_bytes)
with output_widget:
print(f"Step 3: Hash object updated with input bytes.
Intermediate {hash_name} hash value: {hash_object.hexdigest()}")
final_hash = hash_object.hexdigest()
with output_widget:
print(f"Step 4: Final {hash_name} hash: {final_hash}")
return final_hash
OUTPUT:
Text: Hello World
RESULT:
We have successfully executed the source code and the output for
both the algorithsm have been obtained .