Cookie Consent by Free Privacy Policy Generator 📌 Crack the Code Like Caesar: Build Your Own Secret Message Encrypter! [Python code included]


✅ Crack the Code Like Caesar: Build Your Own Secret Message Encrypter! [Python code included]


💡 Newskategorie: Programmierung
🔗 Quelle: dev.to

Image description

The Caesar cipher, also known as the Caesar shift or Caesar’s code, is one of the oldest and simplest encryption techniques in the history of cryptography. It is named after Julius Caesar, the Roman military general and statesman who is believed to have used this method for secure communication with his officials around 58–51 BC. Julius Caesar employed this cipher to protect the confidentiality of his military orders and messages, allowing him to communicate sensitive information without being easily understood by adversaries.

How It Works

The Caesar cipher is a substitution cipher. It involves shifting each letter in the plaintext by a fixed number of positions down or up the alphabet. This shift is known as the key. The original Caesar cipher uses a fixed shift of 3 positions down the alphabet. For example:

A becomes D
B becomes E
Z becomes C (wrapping around the alphabet)

While the Caesar cipher provided a basic level of security for its time, it is relatively simple to break. With only 26 possible keys to try (since the key can be between 0 and 25), a brute-force attack can quickly reveal the plaintext.

Implementing the Caesar Cipher in Python

Let’s write a simple Python program to encrypt and decrypt messages using the Caesar cipher. In this example i will assume to hardcode the alphabets and special characters in SYMBOLS variable.

#caesarCipherv1 take both plaintext and key as input to create a ciphertext

inputtext = input("What is input plaintext:")
key = int(input("What is the caesar key:"))     #try to convert string to
mode = input("encrypt/decrypt:")

# Every possible symbol that can encrypted
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcedfghijklmnopqrstuvwxyz!@#$%^&*()_+0123456789'

outtext = ""

for character in inputtext: 
    if character in SYMBOLS:
        #replace character by the key position
        if mode == 'encrypt':
            index = SYMBOLS.find(character) + key
        elif mode == 'decrypt':
            index = SYMBOLS.find(character) - key

        #print("the %s" % (index))

        if index >= len(SYMBOLS):
            index = index - len(SYMBOLS)
        elif index < 0:
            index = index + len(SYMBOLS)

        outtext = outtext + SYMBOLS[index]
    else:
        outtext = outtext + character

print(outtext)

While the program works well, there are a couple of areas for improvement:

  1. Key Value Limitation: Currently, the key value is limited by the length of the SYMBOL variable. In fact, it can only be up to twice the length of SYMBOL.
  2. Hardcoded Symbols: The SYMBOLS variable is currently hardcoded. This means it’s not very flexible if you want to use a different character set in the future. We can address these limitations in below to make the program even more versatile!
import sys
from colorama  import Fore, init

def caesar_cipher(text, key):
    result = ""
    for character in text:
        #print("%s" % (ord(character)))
        if character.isupper():
            #upper character
            result += chr((ord(character) - 65 + key) % 26 + 65)
        elif character.islower():
            #lower character
            result += chr((ord(character) - 97 + key) % 26 + 97)
        elif ord(character) in range(33, 57):
            #special character
            result += chr((ord(character) - 33 + key) % 25 + 33)
        else:
            #not found cant encrypt
            result += character
    return result

def main():
    try:
        # Get user input
        text = input("Enter the text to encrypt or decrypt:")
        key = int(input("Enter the key value(positive for encryption, negative for decryption):"))

        #caesar function
        cipher_text = caesar_cipher(text, key)

        #print the result
        print(f"{Fore.GREEN}Result:{Fore.RESET} {cipher_text}")
    except ValueError:
        print(f"{Fore.RED}Error:{Fore.RESET} Invalid input. Please enter a valid key value (integer)")

if __name__ == "__main__":
    main()

The caesar_cipher function effectively implements the Caesar cipher algorithm. It takes the plain text message and a key value (positive for encryption, negative for decryption) as input.

Here’s a breakdown of its functionality:

  1. Character Processing: It iterates through each character in the message.
  2. ASCII Conversion: It leverages the built-in ord function to determine the numerical representation (ASCII value) of each character.
  3. Shifting and Wrapping: Based on the character case (uppercase or lowercase) and the key value, it performs the Caesar shift. The function ensures the shift stays within the alphabetical boundaries by using a modulo operation (%). This ensures the encryption 'wraps around' if the shift goes beyond the alphabet's end.
  4. Character Reconstruction: Finally, it converts the shifted numerical value back into its corresponding character using the chr function. In the next article, we will see how to hack Caesar cipher by using either brute-force or frequency analysis.

More cipher source codes can be found at PythonCipher

...

✅ Crack the Code Like Caesar: Build Your Own Secret Message Encrypter! [Python code included]


📈 127.97 Punkte

✅ Learn with Dr. G - Crack the code and reveal a secret with Python and VS code


📈 32.85 Punkte

✅ Caesar Cipher Encryption Using Python: Step-by-Step Tutorial


📈 29.15 Punkte

✅ Decrypting Caesar Cipher Using Python: Step-by-Step Tutorial


📈 29.15 Punkte

✅ Cracking Caesar Cipher Using Brute Force Attack with Python


📈 29.15 Punkte

✅ Build Your Own ChatGPT-like Chatbot with Java and Python


📈 28.86 Punkte

✅ Laravel Framework up to 5.5.40/5.6.29 Token Encrypter.php decrypt X-XSRF-TOKEN Remote Code Execution


📈 27.92 Punkte

✅ CodeLock Encrypter v2.7 - Multiple Web Vulnerabilities


📈 25.44 Punkte

✅ CodeLock Encrypter v2.7 - Multiple Web Vulnerabilities


📈 25.44 Punkte

✅ CodeLock Encrypter v2.7 - Multiple Web Vulnerabilities


📈 25.44 Punkte

✅ CodeLock Encrypter v2.7 - Multiple Web Vulnerabilities


📈 25.44 Punkte

✅ CodeLock Encrypter v2.7 - Multiple Web Vulnerabilities


📈 25.44 Punkte

✅ CodeLock Encrypter v2.7 - Multiple Web Vulnerabilities


📈 25.44 Punkte

✅ An ok batch encrypter


📈 25.44 Punkte

✅ Shell Scripting - File Encrypter/Decrypter


📈 25.44 Punkte

✅ Hyperion Runtime Encrypter 2.0


📈 25.44 Punkte

✅ Hyperion Runtime Encrypter 2.3


📈 25.44 Punkte

✅ Huawei releases it's own desktop PC with their own OS based on Linux and their own ARM CPU.


📈 25.04 Punkte

✅ Pong in my own language in my own graphics library in my own game


📈 25.04 Punkte

✅ Mark Zuckerberg posts a secret code while announcing the secret code feature for WhatsApp


📈 23.63 Punkte

✅ Hail Caesar Trailer


📈 23.31 Punkte

✅ Hail Caesar Trailer


📈 23.31 Punkte

✅ Little Caesar's running Ubuntu in Mexico City


📈 23.31 Punkte

✅ Caesar's rooms still available for DEF CON 23


📈 23.31 Punkte

✅ "Builders of Egypt": Spiritueller Nachfolger von "Caesar III" als große Aufbauspiel-Hoffnung


📈 23.31 Punkte

✅ The New U.S. “Caesar” Sanctions on Syria Are Illegal


📈 23.31 Punkte











matomo

Datei nicht gefunden!