*Welcome! Meet our Python Code Assistant, your new coding buddy. Why wait? Start exploring now!*

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:

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

For the English alphabet **(m)** is typically 26. The values of * (a)* and

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

- 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. - Apply the formula
to get the ciphertext value.**E(x) = ax + b mod m** - 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:

is the decrypted letter corresponding to the ciphertext letter (y).**D(y)**is the modular inverse of**(a**^{-1}), which satisfies**(a)****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 ♥

*Ready for more? Dive deeper into coding with our AI-powered Code Explainer. Don't miss it!*

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!