Caesar cipher
The Caesar cipher is a form of substitution cipher where each letter in the plaintext is shifted a certain number of places (the value of the key) to the right down the character set. For example, with a key of 3, the letter A would be substituted with D (A=0 | 0+3=3 | 3=D), B would become E, and so forth. This technique is named after Julius Caesar, who used it in his personal communications. The possible key values are limited by the number of available characters. If the result of the addition exceeds the number of available characters, it must be reduced by taking the result modulo the size of the character set. This ensures that the resulting index wraps around and corresponds to a valid character within the defined character set. The same applies to keys, e.g., if the number of all characters is 26, and the key is 27, it will yield the same result as key 1.
| A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
Implementation
CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # this string can contain other characters like !, @, etc.
def caesar(message, key, mode):
text = message.upper()
encrypted_text = ""
if mode == "decrypt":
key = -key # negating the key value to reverse the encryption
for char in text: # iterating over each character in the input text
if char in CHARACTERS:
index = CHARACTERS.index(char)
new_index = (index + key) % len(CHARACTERS) # calculating the new index by applying the key and wrapping around using modulo
# "wrapping around" must be used when the new index exceeds the bounds of the CHARACTERS string
encrypted_text += CHARACTERS[new_index] # appending the character at the new index to the encrypted_text variable
else:
encrypted_text += char # if the character is not in CHARACTERS, keep it unchanged
return encrypted_text
message = "Secret message"
key = 13
message = caesar(message, key, "encrypt")
print(message)
message = caesar(message, key, "decrypt")
print(message)
A brute-force attack
A brute-force attack is a method of cracking encryption by systematically trying every possible combination of keys or passwords until the correct one is found. Despite its effectiveness against weak ciphers, like Caesar's, the method becomes impractical against modern encryption techniques, where the complexity and length of keys exponentially increase the time required to succeed.
from caesar import caesar
CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # this string can contain other characters like !, @, etc.
def brute_force_caesar(ciphertext):
for key in range(1, len(CHARACTERS)):
decrypted_message = caesar(ciphertext, key, "decrypt")
print(f"Key {key}: {decrypted_message}")
message = "FRPERG ZRFFNTR"
result = brute_force_caesar(message)
print(result)