Hone logo
Hone
Problems

Simple Caesar Cipher Encryption

You're tasked with implementing a fundamental encryption technique, the Caesar cipher, in Python. This cipher is a substitution cipher where each letter in the plaintext is shifted a certain number of places down or up the alphabet. Understanding this basic encryption method is a great stepping stone to learning more complex cryptographic algorithms.

Problem Description

Your goal is to create a Python function that takes a plaintext string and a shift value as input and returns the encrypted ciphertext.

Requirements:

  • The function should accept two arguments:
    • plaintext: A string representing the message to be encrypted.
    • shift: An integer representing the number of positions to shift each letter.
  • The cipher should only affect uppercase and lowercase English alphabet letters.
  • Other characters (numbers, spaces, punctuation, etc.) should remain unchanged.
  • The shift should wrap around the alphabet. For example, if the shift is 3, 'X' should become 'A', and 'z' should become 'c'.
  • The function should return the resulting ciphertext as a string.

Expected Behavior:

  • If plaintext is "Hello, World!" and shift is 3, the output should be "Khoor, Zruog!".
  • If plaintext is "ABC xyz" and shift is 1, the output should be "BCD yza".
  • If plaintext is "123!" and shift is 5, the output should be "123!".

Edge Cases to Consider:

  • Empty plaintext string.
  • Shift value of 0.
  • Large positive and negative shift values.

Examples

Example 1:

Input: plaintext = "Hello, World!", shift = 3
Output: "Khoor, Zruog!"
Explanation: Each letter is shifted 3 positions forward. 'H' becomes 'K', 'e' becomes 'h', 'l' becomes 'o', 'o' becomes 'r', 'W' becomes 'Z', 'o' becomes 'r', 'r' becomes 'u', 'l' becomes 'o', 'd' becomes 'g'. Punctuation and spaces are unchanged.

Example 2:

Input: plaintext = "abcXYZ", shift = -1
Output: "zabWXY"
Explanation: Each letter is shifted 1 position backward. 'a' becomes 'z', 'b' becomes 'a', 'c' becomes 'b', 'X' becomes 'W', 'Y' becomes 'X', 'Z' becomes 'Y'.

Example 3:

Input: plaintext = "Testing 123", shift = 26
Output: "Testing 123"
Explanation: A shift of 26 is equivalent to a shift of 0 for the English alphabet, so the text remains unchanged.

Constraints

  • The plaintext string can contain any ASCII characters.
  • The shift integer can range from -1000 to 1000.
  • The length of the plaintext string will be between 0 and 1000 characters.

Notes

  • Consider how you will handle uppercase and lowercase letters separately.
  • The modulo operator (%) can be very useful for implementing the wrap-around behavior.
  • Think about how to convert characters to their numerical representations and back.
Loading editor...
python