[Python] Bruteforcing the ceaser cipher

Discussão em 'Python' iniciado por Stack, Agosto 23, 2025.

  1. Stack

    Stack Membro Participativo

    I wanted to write an algorithm for bruteforcing shift ciphers based on the Ceaser cipher decryption algorithm that I implemented in Python as below

    letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    def decrypt(cipher: str):
    "Decrypts text encrtyted in Ceaser's cipher"
    plaintext = []
    for i in cipher:
    p = (letters.find(i) - 3) % 26 #Decryption algorithm: p = (c-k) mod 26
    #where; c is the index of the letter in the alphabet and k is the key
    if i == "-":
    plaintext.append(" ")
    else:
    if p < 0: #if the number is a negative, ignore mod 26 and instead, directly sum to 26
    p = p + 26
    else:
    plaintext.append(letters[p])
    return "".join(plaintext)


    I tried wrapping the code around a while loop to cycle through the possible combinations but everything just broke.

    def bruteforce(cipher: str):
    "Cycles through all possible shifts"
    n = 1
    while n <= 26:
    plaintext = []
    for i in cipher.upper():
    p = (letters.find(i) - n) % 26
    if i == "-":
    plaintext.append(" ")
    else:
    if p < 0:
    p = p + 26
    else:
    plaintext.append(letters[p])

    n += 1
    return "".join(plaintext)


    Any ideas on what I did wrong?

    Continue reading...

Compartilhe esta Página