SL Exp No.4

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

ID :VU4F2223145 Experiment No.

:04 Security Lab

Aim: Design and Implement a Product cipher using Substitution ciphers and
Transposition ciphers.

Program:
def caesar_cipher(text, shift):
result = []
for char in text:
if char.isalpha():
shift_amount = shift % 26
if char.islower():
start = ord('a')
else:
start = ord('A')
result.append(chr(start + (ord(char) - start + shift_amount) % 26))
else:
result.append(char)
return ''.join(result)

def columnar_transposition_cipher(text, key):


num_columns = len(key)
num_rows = len(text) // num_columns + (len(text) % num_columns > 0)

# Pad text to fit grid


text = text.ljust(num_rows * num_columns)

# Create grid
grid = [text[i:i + num_columns] for i in range(0, len(text), num_columns)]

# Order columns based on key


columns = ['' for _ in range(num_columns)]
for i in range(num_columns):
col_index = int(key[i]) - 1
columns[col_index] = ''.join(row[i] for row in grid)

# Concatenate columns
return ''.join(columns)
def product_cipher(plaintext, shift, key):
# Apply Caesar Cipher (Substitution)

TE-IT-A VPPCOE & VA


substituted_text = caesar_cipher(plaintext, shift)

# Apply Columnar Transposition Cipher (Transposition)


encrypted_text = columnar_transposition_cipher(substituted_text, key)

return encrypted_text

def decrypt_product_cipher(ciphertext, shift, key):


# Reverse Columnar Transposition Cipher
num_columns = len(key)
num_rows = len(ciphertext) // num_columns

# Create columns based on key


columns = ['' for _ in range(num_columns)]
for i in range(num_columns):
col_index = int(key[i]) - 1
columns[col_index] = ciphertext[i*num_rows:(i+1)*num_rows]

# Create grid
grid = ['' for _ in range(num_rows)]
for i in range(num_rows):
for j in range(num_columns):
grid[i] += columns[j][i]

# Remove padding
decrypted_text = ''.join(grid).rstrip()

# Apply reverse Caesar Cipher


shift = -shift % 26
return caesar_cipher(decrypted_text, shift)

def main():
plaintext = input("Enter the plaintext: ")
shift = int(input("Enter the shift for Caesar Cipher: "))
key = input("Enter the key for Columnar Transposition Cipher (e.g.,
'3412'): ")

encrypted = product_cipher(plaintext, shift, key)


print(f"Encrypted text: {encrypted}")

decrypted = decrypt_product_cipher(encrypted, shift, key)


print(f"Decrypted text: {decrypted}")

TE-IT-A VPPCOE & VA


if __name__ == "__main__":
main()

Output:

Conclusion:

We have suscessfully Designed and Implemented a Product cipher using


Substitution ciphers and Transposition ciphers.

TE-IT-A VPPCOE & VA

You might also like