

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


/*REXX program supports the  Caesar cypher for the Latin alphabet only,  no punctuation */
/*──────────── or blanks allowed,  all lowercase Latin letters are treated as uppercase.*/
parse arg key .;    arg . p                      /*get key & uppercased text to be used.*/
p= space(p, 0)                                   /*elide any and all spaces (blanks).   */
                    say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/
                    say '       plain text:' p   /*  "   "       plain text    "    "   */
y= Caesar(p, key);  say '         cyphered:' y   /*  "   "    cyphered text    "    "   */
z= Caesar(y,-key);  say '       uncyphered:' z   /*  "   "  uncyphered text    "    "   */
if z\==p  then say  "plain text doesn't match uncyphered cyphered text."
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Caesar: procedure; arg s,k;  @= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        ak= abs(k)                               /*obtain the absolute value of the key.*/
        L= length(@)                             /*obtain the length of the  @  string. */
        if ak>length(@)-1  |  k==0  then  call err k  'key is invalid.'
        _= verify(s, @)                          /*any illegal characters specified ?   */
        if _\==0  then call err 'unsupported character:'   substr(s, _, 1)
        if k>0    then ky= k + 1                 /*either cypher it,  or ···            */
                  else ky= L + 1 - ak            /*     decypher it.                    */
        return translate(s, substr(@ || @,  ky,  L),   @)   /*return the processed text.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
err:    say;      say '***error***';       say;          say arg(1);      say;     exit 13