Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views47 pages

Cryptolab 1

Uploaded by

Rohith Chanda
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)
17 views47 pages

Cryptolab 1

Uploaded by

Rohith Chanda
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/ 47

Cryptography and Network Security Lab

Lab assignment -2

Name: C. Rohith
Register No: 21BCE0810.
Slot: L13 + L14
Name: C. Rohith Register No: 21BCE0810

1. Implement the following substitution cipher techniques without using standard


cryptographic library Functions a. Caesar Cipher b. Vigenère Cipher c. Playfair
Cipher d. Hill cipher e. Data Encryption Standard (DES) f. Simplified Data
Encryption Standard (SDES)
A.
Aim: To implement Caesar cipher without using standard cryptographic library
Functions.
Algorithm:

Caesar Cipher Encryption:

1. Input: A string of text to encrypt (text) and a shift value (shift).


2. Initialize an empty string called result to store the encrypted text.
3. Loop through each character char in the input text:
• If char is an alphabet character:
• If char is uppercase, calculate the encrypted character by adding the
shift value to the ASCII value of char, subtracting the ASCII value of
'A', taking the modulo 26, and then adding the ASCII value of 'A'.
Append this encrypted character to result.
• If char is lowercase, calculate the encrypted character similarly but
using the ASCII values of 'a'.
• If char is not an alphabet character, append char to result unchanged.
4. Return the encrypted text stored in result.

Caesar Cipher Decryption:

1. Input: A string of text to decrypt (text) and a shift value (shift).


2. Decrypt the text by using the Caesar Cipher encryption algorithm with the
negative of the shift value (-shift).
3. Return the decrypted text.

Main Program:

1. Input: Obtain the plaintext to be encrypted and the shift value from the user.
2. Encrypt the plaintext using the Caesar Cipher encryption algorithm with the
provided shift value.
Name: C. Rohith Register No: 21BCE0810

3. Decrypt the encrypted text using the Caesar Cipher decryption algorithm with
the same shift value.
4. Output: Display the original plaintext, the encrypted text, and the decrypted text
to the user along with additional information such as name and registration
number.

Code: def caesar_cipher_encrypt(text,shift):


result = ""
for char in text:
if char.isalpha():
if char.isupper():
result += chr((ord(char)+ shift - ord('A')) % 26 + ord('A'))
else:
result += chr((ord(char) + shift - ord('a')) % 26 + ord('a'))
else:
result += char
return result

def caesar_cipher_decrypt(text,shift):
return caesar_cipher_encrypt(text,-shift)
plaintext = input('enter the plaintext: ')
shift_value = int(input("enter the shift value: "))
encrypted_text = caesar_cipher_encrypt(plaintext,shift_value)
decrpted_text = caesar_cipher_decrypt(encrypted_text,shift_value)
print("Name: C.Rohith")
print("Register No: 21BCE0810")
Name: C. Rohith Register No: 21BCE0810

print("Original Text: ",plaintext)


print("Encrypted: ",encrypted_text)
print("Decrypted: ",decrpted_text)

Screenshot:

Output:
Name: C. Rohith Register No: 21BCE0810

Aim: To implement Vigenère cipher without using standard cryptographic library


Functions.
Algorithm:
1. Input: A plaintext string (plaintext) and a key string (key).
2. Initialize an empty string called ciphertext to store the encrypted text.
3. Repeat: Loop through each character char in the plaintext:
• If char is an alphabet character:
• Determine the shift value for the current character based on the
corresponding character in the key.
• Apply the Vigenère Cipher encryption formula to encrypt the
character.
• Append the encrypted character to the ciphertext.
• If char is not an alphabet character, append it to ciphertext unchanged.
4. Return the encrypted text stored in ciphertext.

Vigenère Cipher Decryption:

1. Input: A ciphertext string (ciphertext) and a key string (key).


2. Initialize an empty string called decrypted_text to store the decrypted text.
3. Repeat: Loop through each character char in the ciphertext:
• If char is an alphabet character:
• Determine the shift value for the current character based on the
corresponding character in the key.
• Apply the Vigenère Cipher decryption formula to decrypt the
character.
• Append the decrypted character to the decrypted_text.
• If char is not an alphabet character, append it to decrypted_text unchanged.
4. Return the decrypted text stored in decrypted_text.

Main Program:

1. Input: Obtain the plaintext and key from the user.


2. Encrypt the plaintext using the Vigenère Cipher encryption algorithm with the
provided key.
3. Decrypt the ciphertext using the Vigenère Cipher decryption algorithm with the
same key.
4. Output: Display the original plaintext, the encrypted text, and the decrypted text
to the user.
Name: C. Rohith Register No: 21BCE0810

Code:
def vigenere_cipher_encrypt(plaintext, key):
ciphertext = ""
key_length = len(key)
for i in range(len(plaintext)):
char = plaintext[i]
if char.isalpha():
if char.isupper():
shift = ord('A')
else:
shift = ord('a')
key_char = key[i % key_length]
if key_char.isupper():
key_shift = ord('A')
else:
key_shift = ord('a')
encrypted_char = chr((ord(char) + ord(key_char) - 2 * shift) % 26 +
shift)
ciphertext += encrypted_char
else:
ciphertext += char
return ciphertext

def vigenere_cipher_decrypt(ciphertext, key):


decrypted_text = ""
key_length = len(key)
for i in range(len(ciphertext)):
char = ciphertext[i]
if char.isalpha():
if char.isupper():
shift = ord('A')
else:
shift = ord('a')
key_char = key[i % key_length]
if key_char.isupper():
key_shift = ord('A')
else:
key_shift = ord('a')
decrypted_char = chr((ord(char) - ord(key_char) + 26) % 26 + shift)
decrypted_text += decrypted_char
else:
decrypted_text += char
return decrypted_text
Name: C. Rohith Register No: 21BCE0810

plaintext = input("Enter the plaintext: ")


key = input("Enter the key: ")

encrypted_text = vigenere_cipher_encrypt(plaintext, key)


decrypted_text = vigenere_cipher_decrypt(encrypted_text, key)

print("Original Text:", plaintext)


print("Encrypted Text:", encrypted_text)
print("Decrypted Text:", decrypted_text)

Output:

Aim: To implement Playfair Cipher without using standard cryptographic library


Functions.
Algorithm:
1. prepare_text Function:
• Input: Text to be prepared (text)
• Output: Prepared text for Playfair cipher
• Initialize an empty string cleaned_text.
• Iterate through each character char in the input text:
• Convert char to uppercase.
• If char is alphabetic:
• If char is the same as the previous character in cleaned_text,
add "X" to cleaned_text.
• Add char to cleaned_text.
• Return cleaned_text.
2. generate_key_square Function:
• Input: Key for generating the key square (key)
• Output: 5x5 key square
• Initialize an empty 5x5 matrix key_square.
• Append remaining uppercase alphabets to the key.
• Remove duplicates from key while maintaining the original order.
• Iterate through each character char in the key:
• Skip "J".
• Insert char into the key_square row by row, skipping "J".
Name: C. Rohith Register No: 21BCE0810

• Return key_square.
3. find_positions Function:
• Input: Key square and two characters (key_square, char1, char2)
• Output: Positions of the two characters in the key square
• Iterate through each row and column of the key square:
• Find the positions of char1 and char2.
• Return the positions (pos1, pos2).
4. encrypt_digraph Function:
• Input: Key square and a digraph (two characters) (key_square, digraph)
• Output: Encrypted digraph
• Find the positions of the two characters in the key square using the
find_positions function.
• If both characters are in the same row, replace them with the characters to
their right (wrapping around if necessary).
• If both characters are in the same column, replace them with the
characters below them (wrapping around if necessary).
• If the characters are in different rows and columns, replace them with the
characters that form a rectangle with them.
• Return the encrypted digraph.
5. encrypt Function:
• Input: Key and plaintext (key, text)
• Output: Encrypted ciphertext
• Generate the key square using the generate_key_square function.
• Prepare the plaintext for encryption using the prepare_text function.
• Encrypt the prepared text in digraphs using the encrypt_digraph function.
• Return the encrypted ciphertext.
6. decrypt Function:
• Input: Key and ciphertext (key, cipher_text)
• Output: Decrypted plaintext
• (Incomplete - Not provided in the given code)
7. Example Usage:
• Define a key (key) and plaintext (text).
• Encrypt the plaintext using the encrypt function and print the encrypted
text.
Name: C. Rohith Register No: 21BCE0810

Code: import string

def prepare_text(text):
"""Prepares text for Playfair cipher by removing non-alphabetic characters,
converting to uppercase, and handling double letters."""
cleaned_text = ""
for i in range(len(text)):
char = text[i].upper()
if char.isalpha():
if i > 0 and char == cleaned_text[-1]:
cleaned_text += "X" # Insert "X" between double letters
cleaned_text += char
return cleaned_text

def generate_key_square(key):
"""Generates the 5x5 key square from the given key."""
key_square = [[None for _ in range(5)] for _ in range(5)]
key += string.ascii_uppercase # Append remaining alphabets
key = "".join(sorted(set(key), key=key.index)) # Remove duplicates and
maintain order

row, col = 0, 0
for char in key:
if char == "J":
continue # Skip "J"
key_square[row][col] = char
col += 1
if col == 5:
col = 0
row += 1
return key_square

def find_positions(key_square, char1, char2):


"""Finds the positions of two characters in the key square."""
pos1 = None
pos2 = None
for i in range(5):
for j in range(5):
if key_square[i][j] == char1:
pos1 = (i, j)
if key_square[i][j] == char2:
pos2 = (i, j)
return pos1, pos2
Name: C. Rohith Register No: 21BCE0810

def encrypt_digraph(key_square, digraph):


"""Encrypts a digraph using the Playfair cipher rules."""
pos1, pos2 = find_positions(key_square, digraph[0], digraph[1])
if pos1[0] == pos2[0]: # Same row
return key_square[pos1[0]][(pos1[1] + 1) % 5] +
key_square[pos2[0]][(pos2[1] + 1) % 5]
elif pos1[1] == pos2[1]: # Same column
return key_square[(pos1[0] + 1) % 5][pos1[1]] + key_square[(pos2[0] + 1)
% 5][pos2[1]]
else: # Different rows and columns
return key_square[pos1[0]][pos2[1]] + key_square[pos2[0]][pos1[1]]

def encrypt(key, text):


"""Encrypts the given text using the Playfair cipher."""
key_square = generate_key_square(key)
prepared_text = prepare_text(text)

cipher_text = ""
for i in range(0, len(prepared_text), 2):
digraph = prepared_text[i:i+2]
cipher_digraph = encrypt_digraph(key_square, digraph)
cipher_text += cipher_digraph

return cipher_text

def decrypt(key, cipher_text):


"""Decrypts the given cipher text using the Playfair cipher."""
# Decryption uses the same logic as encryption, but with inverse operations
key_square = generate_key_square(key)
plain_text = ""

# ... (Implement decryption logic using inverse operations)

return plain_text

# Example usage
key = "MONARCHY"
text = "hide the gold in the tree stump"
encrypted_text = encrypt(key, text)
print(encrypted_text) # Output: BPQCVGKDUVPXGUGMMCOGLQAOB
Name: C. Rohith Register No: 21BCE0810

Output:

Aim: To implement hill cipher program without using standard cryptographic


library functions.
Algorithm:
1. inverseMatrix Function:
Input: A 2x2 matrix key and an integer m.
Output: The inverse of the key matrix modulo m.
Procedure:
Calculate the determinant of the key matrix.
Find the multiplicative inverse of the determinant modulo m.
Compute the elements of the inverse matrix using the determinant inverse.
2. hillCipherEncrypt Function:
Input: Plaintext string plaintext, 2x2 key matrix key, and an integer m.
Output: Ciphertext string obtained by encrypting the plaintext using the Hill Cipher
with the provided key.
Procedure:
Divide the plaintext into blocks of two characters.
For each block:
Convert the characters to their corresponding numerical values.
Perform matrix multiplication with the key.
Take the modulo m of each result.
Convert the resulting numerical values back to characters and append them to the
Name: C. Rohith Register No: 21BCE0810

ciphertext.
3. hillCipherDecrypt Function:
Input: Ciphertext string ciphertext, 2x2 key matrix key, and an integer m.
Name: C. Rohith Register: 21BCE0810
Output: Plaintext string obtained by decrypting the ciphertext using the Hill Cipher
with the provided key.
Procedure:
Compute the inverse of the key matrix modulo m using the inverseMatrix function.
Divide the ciphertext into blocks of two characters.
For each block:
Convert the characters to their corresponding numerical values.
Perform matrix multiplication with the inverse key.
Take the modulo m of each result.
Convert the resulting numerical values back to characters and append them to the
plaintext.
4. main Function:
Input: None.
Output: None (prints the ciphertext and decrypted text).
Procedure:
Initialize a plaintext string and a 2x2 key matrix.
Encrypt the plaintext using the hillCipherEncrypt function and print the ciphertext.
Decrypt the ciphertext using the hillCipherDecrypt function and print the
decrypted text.
5. Output:
Name: C. Rohith Register No: 21BCE0810

Print the ciphertext and decrypted text obtained from the encryption and decryption
processes.
Code:
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> inverseMatrix(vector<vector<int>>& key, int
m) {
int det = key[0][0] * key[1][1] - key[0][1] * key[1][0];
int detInv = 0;
for (int i = 0; i < m; i++) {
if ((det * i) % m == 1) {
detInv = i;
break;
}
}
vector<vector<int>> inv(2, vector<int>(2, 0));
inv[0][0] = (key[1][1] * detInv) % m;
inv[0][1] = (-key[0][1] * detInv) % m;
inv[1][0] = (-key[1][0] * detInv) % m;
inv[1][1] = (key[0][0] * detInv) % m;
return inv;
}
string hillCipherEncrypt(string plaintext, vector<vector<int>>&
key, int m) {
string ciphertext = "";
for (int i = 0; i < plaintext.length(); i += 2) {
int x = plaintext[i] - 'a';
int y = plaintext[i + 1] - 'a';
int newX = (key[0][0] * x + key[0][1] * y) % m;
int newY = (key[1][0] * x + key[1][1] * y) % m;
ciphertext += (char)(newX + 'a');
ciphertext += (char)(newY + 'a');
}
return ciphertext;
}
string hillCipherDecrypt(string ciphertext, vector<vector<int>>&
key, int m) {
string plaintext = "";
vector<vector<int>> invKey = inverseMatrix(key, m);
for (int i = 0; i < ciphertext.length(); i += 2) {
int x = ciphertext[i] - 'a';
Name: C. Rohith Register: 21BCE0810
int y = ciphertext[i + 1] - 'a';
Name: C. Rohith Register No: 21BCE0810

int newX = (invKey[0][0] * x + invKey[0][1] * y) % m;


int newY = (invKey[1][0] * x + invKey[1][1] * y) % m;
plaintext += (char)(newX + 'a');
plaintext += (char)(newY + 'a');
}
return plaintext;
}
int main() {
cout << "Name: C. Rohith" << endl;
cout << "Register No: 21BCE0810" << endl;
string plaintext = "hello";
vector<vector<int>> key = { {1, 2}, {3, 4} };
int m = 26;
string ciphertext = hillCipherEncrypt(plaintext, key, m);
cout << "Ciphertext: " << ciphertext << endl;
string decryptedText = hillCipherDecrypt(ciphertext, key,m);
cout << "Decrypted Text: " << decryptedText << endl;
return 0;
}

Output:
Name: C. Rohith Register No: 21BCE0810

Aim: To implement the above algorithm without using standard cryptographic


library.
Algorithm:
1. Key Generation:
• Input: 64-bit binary key.
• Output: Sixteen 48-bit round keys (K1 to K16).
• Procedure:
• Perform a permutation on the 64-bit key using the initial
permutation (IP) table.
• Split the permuted key into two 32-bit halves, C0 and D0.
• Perform sixteen rounds of key generation:
• Generate sixteen 48-bit round keys using a combination of
shifting, permutation, and compression operations.
2. Encryption:
• Input: 64-bit plaintext and sixteen 48-bit round keys (K1 to K16).
• Output: 64-bit ciphertext.
• Procedure:
• Perform an initial permutation (IP) on the 64-bit plaintext.
• Split the permuted plaintext into two 32-bit halves, L0 and R0.
• Perform sixteen rounds of encryption:
• Expand Rn-1 to 48 bits using the expansion permutation (E)
table.
• XOR the expanded Rn-1 with the round key Kn.
• Apply S-box substitution to the result.
Name: C. Rohith Register No: 21BCE0810

• Permute the result using the permutation (P) table.


• XOR the permuted result with Ln-1 to obtain Rn.
• Set Ln = Rn-1.
• Concatenate Ln and R16 and perform the final permutation (IP^-1)
to obtain the ciphertext.
3. Decryption:
• Input: 64-bit ciphertext and sixteen 48-bit round keys (K1 to K16).
• Output: 64-bit plaintext.
• Procedure:
• Perform the same steps as encryption, but use the round keys K16
to K1 in reverse order during decryption.
Name: C. Rohith Register No: 21BCE0810
4. Permutation Tables:
• IP: Initial permutation table.
• E: Expansion permutation table.
• P: Permutation table used in the function F.
• IP^-1: Final permutation table.
5. S-boxes:
• Eight 4x16 substitution boxes (S1 to S8) are used in the function F for
substituting 6-bit inputs to 4-bit outputs.
6. Initial and Final Permutations:
• The initial and final permutations (IP and IP^-1) are fixed permutations
applied at the beginning and end of the encryption and decryption
processes, respectively.
Name: C. Rohith Register No: 21BCE0810

Code:
# Define permutation tables and S-boxes
INITIAL_PERMUTATION = [58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7]

FINAL_PERMUTATION = [40, 8, 48, 16, 56, 24, 64, 32,


39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25]

SHIFTS = [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]

EXPANSION_PERMUTATION = [32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1]

P_BOX = [16, 7, 20, 21, 29, 12, 28, 17,


1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25]

S_BOX = [
[
[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]
],
# Define other S-boxes here...
Name: C. Rohith Register No: 21BCE0810

def generate_round_keys(key):
# Perform initial permutation on the key
key = initial_permutation(key)
# Split the key into two halves
left_half, right_half = key[:28], key[28:]
round_keys = []
for i in range(16):
# Perform circular left shift on both halves
left_half = left_shift(left_half, SHIFTS[i])
right_half = left_shift(right_half, SHIFTS[i])
# Combine and permute the halves to generate the round key
round_key = final_permutation(left_half + right_half)
round_keys.append(round_key)
return round_keys

def initial_permutation(key):
# Perform initial permutation
return permute(key, INITIAL_PERMUTATION)

def final_permutation(key):
# Perform final permutation
return permute(key, FINAL_PERMUTATION)

def permute(data, table):


# Perform permutation using the given table
return [data[i - 1] for i in table if 1 <= i <= len(data)]

def left_shift(data, n):


# Perform circular left shift
return data[n:] + data[:n]

def des_encrypt(plain_text, round_keys):


# Initial permutation
plain_text = initial_permutation(plain_text)
# Split plaintext into left and right halves
left_half, right_half = plain_text[:32], plain_text[32:]
# Perform 16 rounds of DES
for i in range(16):
Name: C. Rohith Register No: 21BCE0810

left_half, right_half = right_half, xor(left_half, feistel(right_half,


round_keys[i]))
# Final permutation
cipher_text = final_permutation(right_half + left_half)
return cipher_text

def des_decrypt(cipher_text, round_keys):


# Initial permutation
cipher_text = initial_permutation(cipher_text)
# Split ciphertext into left and right halves
left_half, right_half = cipher_text[:32], cipher_text[32:]
# Perform 16 rounds of DES in reverse order
for i in range(15, -1, -1):
left_half, right_half = right_half, xor(left_half, feistel(right_half,
round_keys[i]))
# Final permutation
plain_text = final_permutation(right_half + left_half)
return plain_text

def feistel(data, key):


# Expand 32-bit data to 48 bits
expanded_data = permute(data, EXPANSION_PERMUTATION)
# XOR with round key
xor_result = xor(expanded_data, key)
# Apply S-box substitution
s_box_output = s_box_substitution(xor_result)
# Permute using the P-box
return permute(s_box_output, P_BOX)

def s_box_substitution(data):
s_box_output = []
for i in range(8):
if i * 6 + 5 < len(data): # Check if the index is within range
row = 2 * data[i * 6] + data[i * 6 + 5]
col = 8 * data[i * 6 + 1] + 4 * data[i * 6 + 2] + 2 * data[i * 6 + 3]
+ data[i * 6 + 4]
val = S_BOX[i][row][col]
s_box_output += [int(bit) for bit in bin(val)[2:].zfill(4)]
else:
# Handle the case where the index is out of range
row = 0
col = 0
Name: C. Rohith Register No: 21BCE0810

raise IndexError("Index out of range")


return s_box_output

def xor(data1, data2):


return [(int(bit1) ^ int(bit2)) for bit1, bit2 in zip(data1, data2)]

# Define permutation tables and S-boxes


EXPANSION_PERMUTATION = [32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1]

P_BOX = [16, 7, 20, 21, 29, 12, 28, 17,


1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25]

S_BOX = [
[
[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],
[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]
],
# Define other S-boxes here...
]

# Usage example
key = [1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1,
1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1]
plain_text = [1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]
print("Name: C. Rohith Register No: 21BCE0810")
round_keys = generate_round_keys(key)
cipher_text = des_encrypt(plain_text, round_keys)
print("Encrypted:", cipher_text)
decrypted_text = des_decrypt(cipher_text, round_keys)
print("Decrypted:", decrypted_text)
Name: C. Rohith Register No: 21BCE0810

Aim: To implement the above Simplified Data Encryption Standard (SDES) without
using standard cryptographic
library.
Algorithm:
1. : Input:
• 8-bit plaintext (binary)
• 10-bit key (binary)
2. Key Generation:
• Take a 10-bit binary key as input.
• Generate two 8-bit subkeys, Key1 and Key2, from the input key using the
key generation algorithm.
3. Initial Permutation (IP):
• Permute the plaintext according to the initial permutation (IP) table.
4. Encryption Process:
• Split the permuted plaintext into two 4-bit halves, Left and Right.
• Perform two rounds of encryption:
• Round 1:
• Calculate the output of the F-function using the Right half
and Key1.
• XOR the output of the F-function with the Left half.
• Swap Left and Right halves.
• Round 2:
• Calculate the output of the F-function using the new Right
half and Key2.
• XOR the output of the F-function with the new Left half.
• The result after the second round is the ciphertext.
5. Inverse Initial Permutation (IP^-1):
• Permute the ciphertext according to the inverse initial permutation (IP^-1)
table to obtain the final encrypted output.
6. Decryption Process:
• Decrypting the ciphertext involves performing the same steps as
encryption but using the subkeys in reverse order.
7. Output:
• Display the plaintext, key, encrypted text, and decrypted text.

Key Generation Algorithm:


Name: C. Rohith Register No: 21BCE0810

1. Input:
10-bit key (binary)

2. Generate Subkeys:
• Split the 10-bit key into two 5-bit halves.
• Perform circular left shifts on each 5-bit half according to the key schedule.
• Concatenate the shifted halves to form Key1.
• Perform another set of circular left shifts on each 5-bit half.
• Concatenate the shifted halves to form Key2.

F-function Algorithm:

1. Input:
• 4-bit input (half of the plaintext or ciphertext)
• 8-bit subkey (from key generation)
2. Expansion Permutation (EP):
• Expand the 4-bit input to 8 bits according to the expansion permutation
table.
3. XOR with Subkey:
• XOR the expanded input with the 8-bit subkey.
4. S-box Substitution:
• Divide the XOR result into two 4-bit halves.
• Substitute each 4-bit half using the S-boxes to obtain two 2-bit outputs.
• Concatenate the two 2-bit outputs to form a 4-bit output.
5. Permutation (P4):
• Permute the 4-bit output according to the permutation table P4 to obtain
the final 4-bit output.
Code:
# Key generation for SDES
def generate_key():
key = input("Enter 10-bit key: ")
while len(key) != 10 or not all(bit.isdigit() for bit in key):
print("Key must be a 10-bit binary number.")
key = input("Enter 10-bit key: ")
return key

# Initial Permutation (IP) table


IP = [2, 6, 3, 1, 4, 8, 5, 7]

# Inverse Initial Permutation (IP^-1) table


IP_inverse = [4, 1, 3, 5, 7, 2, 8, 6]
Name: C. Rohith Register No: 21BCE0810

# Expansion permutation (EP) table


EP = [4, 1, 2, 3, 2, 3, 4, 1]

# Permutation (P4) table


P4 = [2, 4, 3, 1]

# S-boxes
S0 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]
S1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]

# Key generation
def key_generation(key):
key1 = [key[0], key[1], key[2], key[3], key[4], key[5]]
key2 = [key[5], key[6], key[7], key[8], key[9], key[0]]
return key1, key2

# Initial permutation (IP)


def initial_permutation(plain_text):
permuted_text = [plain_text[i - 1] for i in IP]
return permuted_text

# Inverse initial permutation (IP^-1)


def inverse_initial_permutation(cipher_text):
permuted_text = [cipher_text[i - 1] for i in IP_inverse]
return permuted_text

# F-function
def f_function(input_bits, sub_key):
# Expansion permutation (EP)
expanded_bits = [input_bits[i - 1] for i in EP]
# XOR with subkey
xor_result = [int(expanded_bits[i]) ^ int(sub_key[i]) for i in
range(len(expanded_bits))]
# S-box substitution
s0_input = [xor_result[0], xor_result[3]]
s1_input = [xor_result[1], xor_result[2]]
s0_row = int(''.join(map(str, s0_input)), 2)
s0_col = int(''.join(map(str, xor_result[4:6])), 2)
s1_row = int(''.join(map(str, s1_input)), 2)
s1_col = int(''.join(map(str, xor_result[6:])), 2)
s0_output = S0[s0_row][s0_col]
s1_output = S1[s1_row][s1_col]
# Permutation (P4)
output = [s0_output, s1_output]
Name: C. Rohith Register No: 21BCE0810

permuted_output = [output[i - 1] for i in P4]


return permuted_output

# Encryption function
def encrypt(plain_text, key):
# Generate subkeys
key1, key2 = key_generation(key)
# Initial permutation
permuted_text = initial_permutation(plain_text)
# Split text into two parts
left_half = permuted_text[:4]
right_half = permuted_text[4:]
# Round 1
f_output = f_function(right_half, key1)
temp = [left_half[i] ^ f_output[i] for i in range(len(left_half))]
left_half = right_half
right_half = temp
# Round 2
f_output = f_function(right_half, key2)
cipher_text = left_half + [right_half[i] ^ f_output[i] for i in
range(len(right_half))]
# Inverse initial permutation
encrypted_text = inverse_initial_permutation(cipher_text)
return encrypted_text

# Decryption function (same as encryption for SDES)


def decrypt(cipher_text, key):
return encrypt(cipher_text, key)

# Main function
def main():
plain_text = input("Enter 8-bit plaintext: ")
key = generate_key()
encrypted_text = encrypt(plain_text, key)
decrypted_text = decrypt(encrypted_text, key)
print("Name: C.Rohith Register No: 21BCE0810")
print("Plaintext:", plain_text)
print("Key:", key)
print("Encrypted Text:", ''.join(map(str, encrypted_text)))
print("Decrypted Text:", ''.join(map(str, decrypted_text)))

if __name__ == "__main__":
main()
Name: C. Rohith Register: 21BCE0810

2. Find the ciphertext from plaintext and reconstruct the plain text from ciphertext
for the following using Playfair cipher manually
• Plain text: COME TO CNS LAB
• Key : THANK YOU

A.
Name: C. Rohith Register: 21BCE0810

3. Find the ciphertext from plaintext and reconstruct the plain text from ciphertext
for the following using Vigenere cipher manually
• Plain text: VELLORE INSTITUTE OF TECHNOLOGY
• Key : SCOPE

A.
Name: C. Rohith Register: 21BCE0810

4. Find the ciphertext from plaintext and reconstruct the plain text from ciphertext
for the following using Hill cipher manually
• Plain text: WELCOME TO VIT
• Key : NICE
Name: C. Rohith Register: 21BCE0810
Name: C. Rohith Register: 21BCE0810

5. Find the ciphertext from plaintext and reconstruct the plain text from ciphertext
for the following using Hill cipher manually
• Plain text: COMPUTER SCIENCE AND ENGINEERING
• Key : ANALYTICS
A.
Name: C. Rohith Register: 21BCE0810
Name: C. Rohith Register: 21BCE0810
Name: C. Rohith Register: 21BCE0810
Name: C. Rohith Register: 21BCE0810
Name: C. Rohith Register: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810
Name: C. Rohith Register No: 21BCE0810

You might also like