'Python caeser cipher function
I want to write a python function that automatically finds the key of any encrypted text and decrypt the text. I want to use the caesar cipher encryption algorithm.
This code is such that, you will enter the rot but I want the code to be able to find the rot by automatically by itself.
import string
from time import sleep
alphabet = string.ascii_lowercase # "abcdefghijklmnopqrstuvwxyz"
def decrypt(text, rot):
decrypted_text = ""
ct = open("rfc8446.txt", "r")
for cipher in text:
if cipher in alphabet: # check if character is an alphabet
position = alphabet.find(cipher) # find the index position of each text
new_position = (position - rot) % 25 # find the new index position to decrypt
new_character = alphabet[new_position] #
decrypted_text += new_character
else:
decrypted_text += cipher
print(decrypted_text)
text = "hnbcnamjh vh krtn unoc vn knqrwm"
rot = 7
decrypt(text, rot)
Solution 1:[1]
this will give you all possible solutions, simply by looping for all rotations.
import string
from time import sleep
def decrypt(text):
for rot in range(26):
alphabet = string.ascii_lowercase # "abcdefghijklmnopqrstuvwxyz"
decrypted_text = ""
for cipher in text:
if cipher in alphabet:
position = alphabet.find(cipher)
new_position = (position - rot) % 25
new_character = alphabet[new_position]
decrypted_text += new_character
else:
decrypted_text += cipher
print(decrypted_text)
text = "hnbcnamjh vh krtn unoc vn knqrwm"
decrypt(text)
however finding the good one is way more complicated since you need to identify which solution "looks" english, using stuff like text plausibility matrices
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ren |
