The Caesar Cipher is one of the simplest and most famous encryption techniques. It shifts each letter in the plaintext by a fixed number of positions down the alphabet.
- Shift (Key): The number of positions to move each letter (typically 1-25)
- Plaintext: The original, unencrypted message
- Ciphertext: The encrypted message
- Symmetry: The same shift is used for both encryption and decryption (but in opposite directions)
For each character in the message:
- If it's a letter, shift it by the key amount
- If the shift goes past 'Z' (or 'z'), wrap around to the beginning of the alphabet
- If it's not a letter (numbers, spaces, punctuation), leave it unchanged
Example with Shift = 3:
A → D
B → E
C → F
...
X → A
Y → B
Z → C
Simply reverse the process by shifting backwards by the same amount.
The implementation uses ASCII character codes:
- Uppercase 'A' = 65, 'Z' = 90
- Lowercase 'a' = 97, 'z' = 122
Step-by-step for encryption:
-
Get the character's position in the alphabet:
position = char.charCodeAt(0) - 'A'.charCodeAt(0)- This converts 'A' → 0, 'B' → 1, ..., 'Z' → 25
-
Add the shift:
newPosition = (position + shift) % 26- Using modulo (%) ensures wrapping (e.g., 25 + 3 = 28 % 26 = 2)
-
Convert back to character:
String.fromCharCode(newPosition + 'A'.charCodeAt(0))- This adds the code back to get the actual character
- Parameters:
message(string): Text to encryptshift(number): Positions to shift (1-25, but any number works due to modulo)
- Returns: Encrypted text
- Example:
encrypt('Hello', 3)→'Khoor'
- Parameters:
encrypted(string): Encrypted textshift(number): Original shift value
- Returns: Decrypted text
- Example:
decrypt('Khoor', 3)→'Hello'
- Parameters:
encrypted(string): Encrypted text with unknown shift
- Returns: Array of 26 objects with all possible decryptions
- Example: Try all shifts automatically to find the correct one
- Only 26 possible shifts, easy to crack with brute force
- Pattern analysis can reveal the shift
- Modern encryption uses complex algorithms (AES, RSA, etc.)
Use this only for:
- Learning cryptography concepts
- CTF (Capture The Flag) challenges
- Simple educational purposes
node demo.jsThis will show various examples of encryption, decryption, and brute force attacks.