Beginner Tutorial on Ciphers with Python
[deleted]

So, this tutorial is about encryption and decryption with Python. We will start with the simplest--the Caesar Cipher, and progress to much more difficult ones, like the Affine Cipher

The Caesar Cipher is very simple, with one assigning a number to each letter and then adding or subtracting the value of each letter by a special key. However, this code can be cracked by brute force when one tries all 26 numbers.

The main formula of this program is:
c = (x + n) % 26
where c is place value of encrypted letter,
x is place value of actual letter,
n is the number that shows us how many positions of letters we have to replace.
to decrypt each letter we’ll use the formula given below:
c = (x – n) % 26
We will be using the ASCII codes for the first program.

Here is the code. We will go over it line by line.

plaintext = input("Enter Message! ")
key = int(input("Enter key: "))

messagespace = "abcdefghijklmnopqrstuvwxyz"

def encrypt(plaintext, key):
ciphertext = ""
for i in range(len(plaintext)):
if(plaintext[i].isalpha() == False):
ciphertext += plaintext[i]
continue
key %= len(messagespace)
index = messagespace.index(plaintext[i]) * key
ciphertext += messagespace[index % len(messagespace) ]

print("Encrypted message: " + encrypt(plaintext,key))

input()

I do not think I have to explain the variable plaintext and key. So, the variable messagespace defines all the chars that can be used in the code. So, right now, uppercase letters, numbers, and other ASCII figures are not added. Next, there is ciphertext, which is the encrypted str. The line for i in range... is a loop that runs for the length of plaintext. This way, the program will not underrun or overrun.

This is the most important bit of code:

if(plaintext[i].isalpha() == False):
ciphertext += plaintext[i]
continue
key %= len(messagespace)
index = messagespace.index(plaintext[i]) * key

First, the if statement checks if everything is in the alphabet(.isalpha, is code is supplementary to the next bit)

Next, we assign the plaintext in to ciphertext, using i to reiterate and change ciphertext to the new version of plaintext. Then, we have the formula bit. we modulo and reassign the message to the key, which will then multiply every index number of plaintext(which was beginning text) by the key, giving a new ciphertext. Last, we return and print ciphertext. Hope this helped!
I will be doing more of these with more difficult ciphers, stay tuned!

You are viewing a single comment. View All
Codemonkey51

PANIK

@hendryxu