Python Program Implements a Basic Monoalphabetic Cipher

Python Program Implements a Basic Monoalphabetic Cipher
Reading Time: 7 minutes

Introduction:

The provided Python program implements a basic monoalphabetic cipher, a type of substitution cipher, which replaces each letter in a message with another letter based on a fixed shift value. This program allows users to encrypt and decrypt messages using the monoalphabetic cipher, providing an example of how simple encryption techniques work.

Algorithm:

  1. Generate Cipher Key (generate_cipher_key(shift)): This function takes a shift value as input and generates a monoalphabetic cipher key. It first defines the English alphabet, then creates a shifted version of the alphabet by slicing it. The shifted alphabet is combined with the remaining part of the alphabet, creating a one-to-one mapping between original and shifted letters. This mapping is stored in a dictionary and returned as the cipher key.
  2. Encrypt Message (encrypt (message, key)): This function takes a message and the key generated by the previous function. It iterates through each character in the message. If the character is a letter, it checks if it is lowercase or uppercase and retrieves the corresponding replacement letter from the cipher key. Non-alphabetic characters are included as they are. The resulting encrypted message is returned.
  3. Decrypt Ciphertext (decrypt (ciphertext, key)): Similar to the encryption process, this function takes a ciphertext and the key as input. It creates a reverse key by swapping keys and values in the original key. Then, it iterates through each character in the ciphertext. If the character is a letter, it retrieves the original letter from the reverse key. Non-alphabetic characters are preserved. The decrypted message is returned.
  4. Main Function (main ()): This is the main program logic. It takes user input for the shift value and whether to encrypt or decrypt a message. Depending on the choice, it prompts the user for the message or ciphertext and uses the appropriate function to perform the desired operation. The result is displayed to the user.

Python Code:

				
					def generate_cipher_key(shift):
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    key = dict(zip(alphabet, shifted_alphabet))
    return key
def encrypt(message, key):
    encrypted_message = ''
    for char in message:
        if char.isalpha():
            if char.islower():
                encrypted_message += key[char]
            else:
                encrypted_message += key[char.lower()].upper()
        else:
            encrypted_message += char
    return encrypted_message
def decrypt(ciphertext, key):
    reverse_key = {v: k for k, v in key.items()}
    decrypted_message = ''
    for char in ciphertext:
        if char.isalpha():
            if char.islower():
                decrypted_message += reverse_key[char]
            else:
                decrypted_message += reverse_key[char.lower()].upper()
        else:
            decrypted_message += char
    return decrypted_message
def main():
    shift = int(input("Enter the shift value for the cipher: "))
    key = generate_cipher_key(shift)

    choice = input("Encrypt or decrypt? (e/d): ").lower()
    if choice == 'e':
        plaintext = input("Enter the message to encrypt: ")
        encrypted = encrypt(plaintext, key)
        print("Encrypted message:", encrypted)
    elif choice == 'd':
        ciphertext = input("Enter the message to decrypt: ")
        decrypted = decrypt(ciphertext, key)
        print("Decrypted message:", decrypted)
    else:
        print("Invalid choice. Please enter 'e' for encrypt or 'd' for decrypt.")

if __name__ == "__main__":
    main()

				
			

Input :

				
					Enter the shift value for the cipher: 5
Encrypt or decrypt? (e/d): e
Enter the message to encrypt: systech trichy
				
			

Output:

				
					Encrypted message: xdxyjhm ywnhmd
				
			

Explanation:

The program begins by defining three functions: generate_cipher_key(), encrypt(), and decrypt(). The generate_cipher_key() function creates a monoalphabetic cipher key by shifting the alphabet based on the provided shift value. The encrypt () function encrypts a given message using the generated key, while the decrypt () function decrypts a given ciphertext using the reverse key.

In the main () function, the program starts by taking user input for the shift value and operation choice (encryption or decryption). Depending on the choice, it takes the message or ciphertext input from the user and processes it using the corresponding function. The result is then displayed to the user.

This program provides a simple example of how monoalphabetic ciphers work, allowing users to experiment with basic encryption and decryption techniques. However, it’s important to note that monoalphabetic ciphers are not secure for modern cryptography due to their vulnerability to frequency analysis attacks.