

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


 
--caesar cipher for Rosetta Code wiki
--User:Lnettnay
 
--usage eui caesar ->default text, key and encode flag 
--usage eui caesar 'Text with spaces and punctuation!' 5 D
--If text has imbedded spaces must use apostophes instead of quotes so all punctuation works
--key = integer from 1 to 25, defaults to 13
--flag = E (Encode) or D (Decode), defaults to E
--no error checking is done on key or flag
 
include std/get.e
include std/types.e
 
 
sequence cmd = command_line()
sequence val
-- default text for encryption
sequence text = "The Quick Brown Fox Jumps Over The Lazy Dog."
atom key = 13 -- default to Rot-13
sequence flag = "E" -- default to Encrypt
atom offset
atom num_letters = 26 -- number of characters in alphabet
 
--get text
if length(cmd) >= 3 then
	text = cmd[3]
end if
 
--get key value
if length(cmd) >= 4 then
	val = value(cmd[4])
	key = val[2]
end if
 
--get Encrypt/Decrypt flag
if length(cmd) = 5 then
	flag = cmd[5]
	if compare(flag, "D") = 0 then
		key = 26 - key
	end if
end if
 
for i = 1 to length(text) do
	if t_alpha(text[i]) then
		if t_lower(text[i]) then
			offset = 'a'
		else 
			offset = 'A'
		end if
		text[i] = remainder(text[i] - offset + key, num_letters) + offset
	end if
end for
 
printf(1,"%s\n",{text})
 
 