| by Arround The Web | No comments

Affine Cipher Encryption Using Python

Topic of Contents:

  1. Introduction
  2. Prerequisite Knowledge
  3. Affine Cipher Equation
  4. Affine Cipher Encryption Using Python
  5. Proof of Concept
  6. Conclusion
  7. Frequently Asked Questions (FAQs)

The Affine cipher represents a specific kind of substitution cipher, falling under the category of monoalphabetic ciphers. Unlike the more famous Caesar cipher, which shifts each letter in plaintext by a fixed three number of positions, the Affine cipher employs two keys (a and b). Choosing the keys should need special consideration.

Prerequisite Knowledge

In order to understand deeply about today’s topic, you have to understand the following concepts:

  • The Greatest Common Divisor (GCD) & Co-prime number
  • Modular arithmetic

Those concepts areexplained in detail in the previous article entitled “Affine Cipher Mathematical Approach”.

Affine Cipher Equation

Let’s begin with the formula for the Affine cipher encryption:

E(x) = (a.x + b) mod m
E(x) Denotes an Encryption of the x alphabetical index
a An index value of the “special” first key
x An index value of the plain letter
b An index value of the second key (additional shift value)
mod m The modulo operations of the total amount of the alphabet which is 26


Alt-image & caption: Affine Cipher Equation

For example, we want to encrypt the “BIMANDO” plaintext with the 7 and 13 keys. Using the following table index, we first convert the plaintext into its corresponding number:


Alt-image & caption: Index Numbering

The “BIMANDO” plaintext is converted into an indexing number to “1 8 12 0 13 3 14”.


Alt-image & caption: Convert a Plaintext into an Index Numbering Value

Then, we apply the equation calculation, and the result is shown as follows:


Alt-image & caption: Affine Ciphering

So, the “BIMANDO” plaintext is encrypted using Affine cipher with keys 7 and 13 which results in “URTNAIH”.

Affine Cipher Encryption Using Python

Now, let’s say we want to send a confidential message that contains a bunch of paragraphs. Doing Affine cipher encryption with the manual process takes a lot of effort and time, and has a high chance of miss calculation, right? Therefore, we need a program that automates the Affine Cipher encryption process. The following is the step-by-step process to create a Python program:

1. Import the Required Libraries
Our program begins by importing the necessary modules such as argparse, string, and os for command-line argument parsing, string operations, and operating system-related functionality, respectively.

import argparse
import string
import os

2. Defining Alphabet Mapping
Then, we define the alphabet as a string of lowercase English letters. This is used for mapping the characters during the encryption process later.

alphabet = string.ascii_lowercase

3. Affine Cipher Encryption Function
This is the core function of our program. It takes the input text and two keys, “a” and “b”, and applies the Affine cipher encryption to the text, preserving the text’s structure.

def affine_cipher_encryption(text, a, b):
    encrypted_text = ""
    for char in text:
        if char.lower() in alphabet:
            if char.isupper():
                encrypted_text += chr(((a * (ord(char.lower()) - 97) + b) % 26) + 65)
            else:
                encrypted_text += chr(((a * (ord(char) - 97) + b) % 26) + 97)
        else:

4. Conditional Main Checking
In this block code, check if it’s being executed as the main program. It sets up the argument parser with descriptions for the script and its arguments. The required argument is only a path of a text file input. When we don’t specify the output path, we want it to set a default to the input file name with “_encrypted” appended to it. For the “keys” argument, we want it to be formatted to “a,b”. But if we set it, the default is 5 and 8.

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Affine Cipher Encryption from a text file")
    parser.add_argument("input_file", help="Path to the input text file")
    parser.add_argument("-k", "--keys", type=str, default="5,8", help="Keys for the Affine Cipher in the format 'a,b'")
    args = parser.parse_args()

    a, b = map(int, args.keys.split(','))

    with open(args.input_file, "r") as file:
        text = file.read()

    # Extract the file name from the input file path
    input_filename, extension = os.path.splitext(args.input_file)
    default_output_file = input_filename + "_encrypted" + extension

    # Encrypt the text using the affine cipher
    encrypted_text = affine_cipher_encryption(text, a, b)

    # Write the encrypted text to a new file
    with open(default_output_file, "w") as file:
        file.write(encrypted_text)

Finally, once the encryption function is done, our program will save the output with the same file extension as the input file.

Now, save it to “affine_cipher.py”. Now, run the program by typing the following command:

python affine_cipher.py -h

If you find no error, the output looks like the following image:


Alt-image & caption: Affine Cipher Python Program

Proof of Concept

We have a confidential message with the following “message.txt” name, and we want to broadcast it to our members:


Alt-image & caption: Plaintext

So, we use the program that we created before we want to encrypt this message using Affine cipher with the keys 3 and 7. The command is as follows:

python affine_cipher.py message.txt -k 3,7


Alt-image & caption: Affine Cipher Python Program

With the speed of a blink of an eye, the encrypted message is successfully created and saved to “message_encrypted.txt”. Let’s check what the message looks like:


Alt-image & caption: Affine Ciphertext

As you can see, the message is scrambled. Only our members who know the cipher method and its keys are able to decrypt the message.

Try It Yourself

Download this program source code on our GitHub page at https://github.com/bimando/Affine-Cipher.

Conclusion

In conclusion, the Affine cipher encryption method, a form of monoalphabetic substitution cipher, offers enhanced security through the utilization of two keys, demanding a careful consideration during key selection. Understanding the concepts like the Greatest Common Divisor (GCD), co-prime numbers, and modular arithmetic are essential for grasping the intricacies of the Affine cipher.

The Affine cipher equation, E(x) = (a.x + b) mod m, serves as the fundamental tool for encryption where “a” and “b” represent the keys and “x” symbolizes the plaintext letter’s index. The implementation of an automated Python program for the Affine cipher encryption process was demonstrated to streamline the large-scale encryption tasks efficiently. The program incorporates the key functionalities including importation of libraries, alphabet mapping, an encryption function, and command-line argument parsing for input and output paths. Notably, the script enables the default settings for the keys and output file names to facilitate a seamless encryption process.

Frequently Asked Questions (FAQs)

Q1: What is the Affine cipher and how does it differ from the Caesar cipher?

A1: The Affine cipher is a type of monoalphabetic substitution cipher that employs two keys, “a” and “b”, for encryption. In contrast, the Caesar cipher utilizes a fixed shift of three positions for each letter in the plaintext.

Q2. What are the prerequisites for understanding the Affine cipher?

A2: To comprehend the Affine cipher thoroughly, it is crucial to have a grasp of concepts such as the Greatest Common Divisor (GCD), co-prime numbers, and modular arithmetic.

Q3: How can I encrypt a message using the Affine cipher in Python?

A3: To automate the Affine cipher encryption process, you can utilize the Python program that is outlined in the article. The program efficiently encrypts large-scale text inputs, simplifying the encryption procedure. The article provides step-by-step instructions on importing the libraries, defining the alphabet mapping, creating the encryption function, and parsing the command-line arguments for input and output paths.

Share Button

Source: linuxhint.com

Leave a Reply