How to Implement the Affine Cipher in Python

Discover the Affine Cipher in Python: a straightforward tutorial blending historical cryptography with modern coding, perfect for enthusiasts and programmers.
  · 6 min read · Updated feb 2024 · Ethical Hacking · Python Standard Library · Cryptography

Before we get started, have you tried our new Python Code Assistant? It's like having an expert coder at your fingertips. Check it out!

In this tutorial, we’re paying a special visit to classical cryptography - We will see how to implement the Affine cipher and use it to encrypt our plaintexts or messages.

The history of the Affine Cipher is deeply rooted in the ancient world, finding its earliest applications in classical cryptography. The fundamental concept of shifting letters, akin to the Caesar Cipher, traces back to Julius Caesar in ancient Rome. However, the Affine Cipher, as a more advanced monoalphabetic substitution cipher, gained prominence through contributions from Arabic scholars during the Islamic Golden Age.

The Affine cipher is a type of monoalphabetic substitution cipher, which means that it is a method of encrypting plaintext by replacing each letter with another letter. The key feature of the affine cipher is that it uses a simple mathematical function to perform the substitution.

The Affine cipher operates on the mathematical formula:

E(x) = (ax + b) mod m

Here:

  • E(x) is the ciphertext letter corresponding to the plaintext letter (x).
  • (a) and (b) are the key components of the cipher.
  • (m) is the size of the alphabet (number of letters).

For the English alphabet (m) is typically 26. The values of (a) and (b) must be chosen such that (a) and (m) are coprime (i.e., they have no common factors other than 1). This ensures that each letter in the plaintext is uniquely mapped to a letter in the ciphertext.

To encrypt a letter using the affine cipher, you follow these steps:

  1. Assign a numerical value to the plaintext letter. For example, you might use the letter's position in the alphabet, with A being 0, B being 1, and so on.
  2. Apply the formula E(x) = ax + b mod m to get the ciphertext value.
  3. Convert the ciphertext value back to a letter using the same numerical mapping used in step 1.

The decryption process involves finding the modular inverse of (a) (if it exists) and using it to reverse the encryption process. The formula for decryption is:

 D(y) = a-1(y - b) mod m 

Here:

  • D(y) is the decrypted letter corresponding to the ciphertext letter (y).
  • (a-1) is the modular inverse of (a), which satisfies a · a-1 ≡ 1 (mod m)

I know I may have bored you with all these equations, but let’s see how to implement the Affine cipher in Python!

Open up a new Python file and follow along! We’re using Python 3.6+, by the way. 

First, install colorama for fancy text coloring:

$ pip install colorama

As usual, we start by importing the necessary modules/libraries:

# Import necessary libraries.
import string
from colorama import init, Fore

# Initialise colorama.
init()

The string module provides a collection of constants and functions specific to string manipulation. It is part of the Python standard library, and its purpose is to offer convenient tools for working with strings.

Next, we create a function to perform the encryption using the concepts discussed above (that is why I took time to discuss the mode of operation):

def affine_encryption(plaintext, a, b):
   # Define the uppercase alphabet.
   alphabet = string.ascii_uppercase
   # Get the length of the alphabet
   m = len(alphabet)
   # Initialize an empty string to store the ciphertext.
   ciphertext = ''
   # Iterate through each character in the plaintext.
   for char in plaintext:
       # Check if the character is in the alphabet.
       if char in alphabet:
           # If it's an alphabet letter, encrypt it.
           # Find the index of the character in the alphabet.
           p = alphabet.index(char)
           # Apply the encryption formula: (a * p + b) mod m.
           c = (a * p + b) % m
           # Append the encrypted character to the ciphertext.
           ciphertext += alphabet[c]
       else:
           # If the character is not in the alphabet, keep it unchanged.
           ciphertext += char
   # Return the encrypted ciphertext.
   return ciphertext

In this function, similar to what we discussed earlier, we are implementing the Affine cipher. It’s pretty straightforward.

Finally, we get user input and perform the encryption:

# Define the plaintext and key components.
plaintext = input(f"{Fore.GREEN}[?] Enter text to encrypt: ")
a = 3
b = 10
# Call the affine_encrypt function with the specified parameters.
encrypted_text = affine_encryption(plaintext, a, b)
# Print the original plaintext, the key components, and the encrypted text.
print(f"{Fore.MAGENTA}[+] Plaintext: {plaintext}")
print(f"{Fore.GREEN}[+] Encrypted Text: {encrypted_text}")

The uniqueness and strength of this program depend on the values of a and b. But remember, the value of a must be coprime with 26 (m - number of alphabets). Feel free to play with the values.

And that’s it! Let’s proceed to run our code:

$ python affine_cipher.py
[?] Enter text to encrypt: PYTHON
[+] Plaintext: PYTHON
[+] Encrypted Text: DEPFAX

Notice that when I passed an input text to be encrypted, I passed it in uppercase. Please do so, too; otherwise, your message won’t be encrypted.

With that, we’re done! This is how you encrypt a message via the Affine Cipher. To learn how to crack the Affine Cipher, check this tutorial out!

Please note that the Affine cipher is an old encryption mechanism, and it is not considered secure as it can easily be cracked. However, this tutorial was for educational purposes. You can use the Affine cipher to make and solve puzzles with your friends!

Check out similar tutorials:

Finally, as we wrap up our journey through the intriguing world of the Affine Cipher, it's clear that the realms of cryptography and Python together open a vast landscape for exploration, learning, and innovation. For those captivated by the elegance of cryptography and the power of Python, delving deeper into this intersection can be both rewarding and enlightening. Our eBook on Cryptography with Python is a comprehensive guide designed to gently elevate your journey from the foundational concepts we've touched upon here to more complex and contemporary cryptographic techniques. It's an invitation to deepen your understanding and enhance your skills at your own pace, expanding your toolkit for both personal projects and professional endeavors in the fascinating world of digital security. Check it out here.

Happy ciphering ♥

Just finished the article? Why not take your Python skills a notch higher with our Python Code Assistant? Check it out!

View Full Code Create Code for Me
Sharing is caring!



Read Also



Comment panel

    Got a coding query or need some guidance before you comment? Check out this Python Code Assistant for expert advice and handy tips. It's like having a coding tutor right in your fingertips!