Caesar Cipher
March 11, 2014
I was asked about a caesar cipher the other day, and suggested that my questioner search for caesar cipher here at Programming Praxis. To my surprise, I discovered that we have never done a caesar cipher (we did the ROT13 cipher, but not a general-purpose caesar cipher), so I apologized to my friend and wrote today’s exercise.
A caeser cipher, named after Julius Caesar, who either invented the cipher or was an early user of it, is a simple substitution cipher in which letters are substituted at a fixed distance along the alphabet, which cycles; children’s magic decoder rings implement a caesar cipher. Non-alphabetic characters are passed unchanged. For instance, the plaintext PROGRAMMINGPRAXIS is rendered as the ciphertext SURJUDPPLQJSUDALV with a shift of 3 positions.
Your task is to write functions that encipher and decipher text using a caesar cipher. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
What should be the cipher key ?
the key is the shift distance
Here’s a solution in Julia. There’s also a one-liner, encipherOneLiner.
The Caesar cipher shows up in Graham Hutton’s *great* book on Haskell.
Here’s a version similar to @Daniel’s:
import Data.Char (chr, isAsciiUpper, ord)
shift :: Int -> Char -> Char
shift n c | isAsciiUpper c = chr $ a + ((n + (ord c – a) `mod` 26))
| otherwise = c
where
a = ord ‘A’
caesar :: Int -> String -> String
caesar n = map $ shift n
main :: IO ()
main = mapM_ putStrLn [p, c, p’]
where
p = "PROGRAMMING PRAXIS"
c = caesar 3 p
p’ = caesar (-3) c
Apologies for the crap formatting. Apparently I’m really out of practice!
Racket / Rackjure
Full writeup: jverkamp.com
python solution:
To bring the cypher up to the current century, we can use an alphabet containing all the uppercase Unicode characters.
{code}
def CeaserC(word,offset=1):
#final=[chr(ord(i)+offset) for i in word]
return (”.join([chr(ord(i)+offset) for i in word]))
def Ceaserback(word,offset=1):
#final=[chr(ord(i)-offset) for i in word]
return (”.join([chr(ord(i)-offset) for i in word]))
print (CeaserC(“thisisatest”,1))
print (Ceaserback(“uijtjtbuftu”))
{/code}
Here’s a Java solution: