-3

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)

Dharman
  • 30,962
  • 25
  • 85
  • 135
Gibson
  • 1
  • 3
  • 1
    Could you show what you've got already? As a hint you might want to look at ord() and chr() which gives you the ascii value of a letter or converts the number into a letter as well as the modulo operator % which lets you make sure you stay within the range of 0-26. – haxor789 Apr 12 '22 at 12:22
  • 2
    Actually ... the real goal of StackOverflow is you build a library of Questions and Answers that is useful to all people. Helping people find bugs is incidental to the real goal. – Stephen C Apr 13 '22 at 12:09
  • Please read [this](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions) – Leo Apr 13 '22 at 12:09
  • I found the interesting answer here: https://stackoverflow.com/a/40976011/13739319 – Gibson Apr 13 '22 at 12:48

1 Answers1

0

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

Ren
  • 157
  • 12