

Task

Implement a Caesar cipher, both encoding and decoding. 

The key is an integer from 1 to 25.

This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).

The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).

So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".

This simple "mono-alphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.

Caesar cipher is identical to Vigenère cipher with a key of length 1. 

Also, Rot-13 is identical to Caesar cipher with key 13.



Related tasks

 Rot-13
 Substitution Cipher
 Vigenère Cipher/Cryptanalysis


fun readfile () = readfile []
           | x = let val ln = readln ()
                 in if eof ln then
                      rev x
                    else
                      readfile ` ln :: x
                 end
 
local	
	val lower_a = ord #"a";
	val lower_z = ord #"z";
	val upper_a = ord #"A";
	val upper_z = ord #"Z";
 
	fun which 
			(c_upper c) = (upper_a, upper_z)
		|	_	    = (lower_a, lower_z)
		;
 
	fun scale 
			(c, az) where (c > #1 az) = scale( (#0 az + (c - #1 az - 1)), az)
		|	(c, az) 		  = c
 
in
	fun encipher
			([], offset, t)                             = implode ` rev t
		|	(x :: xs, offset, t) where (c_alphabetic x) = encipher (xs, offset, (chr ` scale (ord x + offset, which x)) :: t)
		|	(x :: xs, offset, t)                        = encipher (xs, offset, x :: t)
		|	(s, offset) 				    = if (offset < 0) then 
									encipher (explode s, 26 + (offset rem 26), [])
								      else
									encipher (explode s, offset rem 26, [])
end
 
fun default 
		(false, y) = y 
	|	(x,     _) = x
 
;
map println ` map (fn s = encipher (s,ston ` default (argv 0, "1"))) ` readfile ();
 