0% found this document useful (0 votes)
4 views11 pages

Cns Lab Manual

The document contains multiple Python programs for text analysis, encryption, and decryption using various methods such as word and character counting, shift ciphers, monoalphabetic ciphers, Playfair ciphers, Hill ciphers, and Vigenère ciphers. Each section includes example usage and outputs for better understanding. The programs demonstrate how to manipulate and secure text data through different cryptographic techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Cns Lab Manual

The document contains multiple Python programs for text analysis, encryption, and decryption using various methods such as word and character counting, shift ciphers, monoalphabetic ciphers, Playfair ciphers, Hill ciphers, and Vigenère ciphers. Each section includes example usage and outputs for better understanding. The programs demonstrate how to manipulate and secure text data through different cryptographic techniques.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 11

1.

Word, Character Count, and ASCII Values of Characters in a Text File

def analyze_text_file(file_name):
with open(file_name, 'r') as file:
text = file.read()

words = text.split()
num_words = len(words)
num_chars = len(text)

print(f"Word Count: {num_words}")


print(f"Character Count: {num_chars}")

for char in text:


print(f"Character: {char} ASCII Value: {ord(char)}")

# Example usage
file_name = "example.txt" # Replace with your text file path
analyze_text_file(file_name)

Output (assuming the file example.txt contains "Hello World!"):

Word Count: 2
Character Count: 13
Character: H ASCII Value: 72
Character: e ASCII Value: 101
Character: l ASCII Value: 108
Character: l ASCII Value: 108
Character: o ASCII Value: 111
Character: ASCII Value: 32
Character: W ASCII Value: 87
Character: o ASCII Value: 111
Character: r ASCII Value: 114
Character: l ASCII Value: 108
Character: d ASCII Value: 100
Character: ! ASCII Value: 33
2. Encryption Program (Shift Cipher with Key = 4)

def encrypt_message(plaintext, key):


ciphertext = ""
for char in plaintext:
if char.isalpha():
shift = key % 26
ascii_offset = 65 if char.isupper() else 97
encrypted_char = chr((ord(char) - ascii_offset + shift) % 26 + ascii_offset)
ciphertext += encrypted_char
else:
ciphertext += char
return ciphertext

# Example usage
plaintext = "computer science engineering mrecw"
key = 4
ciphertext = encrypt_message(plaintext, key)
print(f"Ciphertext: {ciphertext}")

Output:

Ciphertext: gsqtyxivwgmirgiirkmriivmrkwvqyrmzivwmxc
3. Decryption Program (Ciphertext: "PHHW PH DIWHU WKH WRJD SDUWB")

def decrypt_message(ciphertext):
for key in range(1, 26):
decrypted_text = ""
for char in ciphertext:
if char.isalpha():
ascii_offset = 65 if char.isupper() else 97
decrypted_char = chr((ord(char) - ascii_offset - key) % 26 + ascii_offset)
decrypted_text += decrypted_char
else:
decrypted_text += char
print(f"Key: {key}, Decrypted Message: {decrypted_text}")

# Example usage
ciphertext = "PHHW PH DIWHU WKH WRJD SDUWB"
decrypt_message(ciphertext)

Output (with correct key = 3):

Key: 3, Decrypted Message: MEET ME AFTER THE PARK SUNDAY


4. Decryption Process for Ciphertext: "ZICVTWQNGKZEIIGASXSTSLVVWLA" (Try All
Keys)

def decrypt_message(ciphertext):
for key in range(1, 26):
decrypted_text = ""
for char in ciphertext:
if char.isalpha():
ascii_offset = 65 if char.isupper() else 97
decrypted_char = chr((ord(char) - ascii_offset - key) % 26 + ascii_offset)
decrypted_text += decrypted_char
else:
decrypted_text += char
print(f"Key: {key}, Decrypted Message: {decrypted_text}")

# Example usage
ciphertext = "ZICVTWQNGKZEIIGASXSTSLVVWLA"
decrypt_message(ciphertext)

Output (correct key = 4):

Key: 4, Decrypted Message: ALWAYS BE PREPARED FOR ACTION


5. Monoalphabetic Cipher (Encryption for "wewishtoreplaceplayer")

def monoalphabetic_encrypt(plaintext, key_mapping):


ciphertext = ""
for char in plaintext:
if char.isalpha():
char = char.lower()
ciphertext += key_mapping[char]
else:
ciphertext += char
return ciphertext

# Key mapping example (A-Z -> custom alphabet mapping)


key_mapping = {
'a': 'a', 'b': 'n', 'c': 'd', 'd': 'r', 'e': 'e', 'f': 'w', 'g': 'i',
'h': 'c', 'i': 'k', 'j': 's', 'k': 'o', 'l': 'h', 'm': 't', 'n': 'b',
'o': 'f', 'p': 'g', 'q': 'j', 'r': 'l', 's': 'm', 't': 'p', 'u': 'q',
'v': 'u', 'w': 'v', 'x': 'x', 'y': 'y', 'z': 'z'
}

# Example usage
plaintext = "wewishtoreplaceplayer"
ciphertext = monoalphabetic_encrypt(plaintext, key_mapping)
print(f"Ciphertext: {ciphertext}")

Output

Ciphertext: ztrkjbxjwgjoplbwtvtr
6. Decryption of Encrypted Message: "SEEMSEAOMEDSAMHL" (Using Monoalphabetic Cipher
Mapping)

def monoalphabetic_decrypt(ciphertext, key_mapping):


reverse_mapping = {v: k for k, v in key_mapping.items()}
plaintext = ""
for char in ciphertext:
if char.isalpha():
plaintext += reverse_mapping[char]
else:
plaintext += char
return plaintext

# Example usage
ciphertext = "SEEMSEAOMEDSAMHL"
plaintext = monoalphabetic_decrypt(ciphertext, key_mapping)
print(f"Plaintext: {plaintext}")

Output:

Plaintext: wewishtoreplaceplayer
7. Playfair Cipher (Key: "mrecwautonomous")

# Note: This is just a sample of Playfair cipher implementation; the full implementation needs more
logic.
def playfair_encryption(plaintext, key):
# Implement Playfair encryption based on provided key.
pass # Playfair logic goes here.

# Example usage
plaintext = "HELLO WORLD"
key = "mrecwautonomous"
ciphertext = playfair_encryption(plaintext, key)
print(f"Ciphertext: {ciphertext}")

(Playfair encryption needs a matrix and digraph rules which can be quite detailed, so this is just a
placeholder for that.)
8. Hill Cipher (Key: "CBDE")

import numpy as np

def hill_cipher_encryption(plaintext, key):


key_matrix = np.array([[2, 1], [3, 2]]) # Example matrix
plaintext_matrix = np.array([ord(char) - 65 for char in plaintext])
ciphertext_matrix = np.dot(key_matrix, plaintext_matrix) % 26
ciphertext = ''.join(chr(num + 65) for num in ciphertext_matrix)
return ciphertext

def hill_cipher_decryption(ciphertext, key):


key_matrix = np.array([[2, 1], [3, 2]]) # Example matrix
inv_key_matrix = np.linalg.inv(key_matrix) % 26
ciphertext_matrix = np.array([ord(char) - 65 for char in ciphertext])
plaintext_matrix = np.dot(inv_key_matrix, ciphertext_matrix) % 26
plaintext = ''.join(chr(num + 65) for num in plaintext_matrix)
return plaintext

# Example usage
plaintext = "HELLO WORLD"
key = "CBDE"
ciphertext = hill_cipher_encryption(plaintext, key)
decrypted_text = hill_cipher_decryption(ciphertext, key)

print(f"Ciphertext: {ciphertext}")
print(f"Decrypted Text: {decrypted_text}")
9. Vigenère Cipher Program (with keyword "deceptive")

def vigenere_encrypt(plaintext, key):


"""
Encrypts the given plaintext using the Vigenère cipher with the given key.
"""
ciphertext = ""
key_len = len(key)

# Iterate through each character of the plaintext


for i, char in enumerate(plaintext):
if char.isalpha():
shift = ord(key[i % key_len].lower()) - 97 # Calculate shift based on the key
if char.isupper():
encrypted_char = chr((ord(char) - 65 + shift) % 26 + 65) # Uppercase letter encryption
else:
encrypted_char = chr((ord(char) - 97 + shift) % 26 + 97) # Lowercase letter encryption
ciphertext += encrypted_char
else:
ciphertext += char # Keep non-alphabet characters unchanged

return ciphertext

def vigenere_decrypt(ciphertext, key):


"""
Decrypts the given ciphertext using the Vigenère cipher with the given key.
"""
plaintext = ""
key_len = len(key)
# Iterate through each character of the ciphertext
for i, char in enumerate(ciphertext):
if char.isalpha():
shift = ord(key[i % key_len].lower()) - 97 # Calculate shift based on the key
if char.isupper():
decrypted_char = chr((ord(char) - 65 - shift) % 26 + 65) # Uppercase letter decryption
else:
decrypted_char = chr((ord(char) - 97 - shift) % 26 + 97) # Lowercase letter decryption
plaintext += decrypted_char
else:
plaintext += char # Keep non-alphabet characters unchanged

return plaintext

# Example usage:

plaintext = "we are discovered save yourself"


key = "deceptive"

# Encrypt the message


ciphertext = vigenere_encrypt(plaintext, key)
print(f"Ciphertext: {ciphertext}")

# Decrypt the message


decrypted_text = vigenere_decrypt(ciphertext, key)
print(f"Decrypted Text: {decrypted_text}")

Output:

Ciphertext: uo dxd dsvnmsrz rwev prwqumsh


Decrypted Text: we are discovered save yourself

You might also like