

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


 
lowers = ['a','z']
uppers = ['A','Z']
function void caesar_encode(message:ptr key:uint) {
  len = strlen$ message
  for uint [0u,len) with index {
    temp = deref_ubyte$ + message index
    if in temp lowers {
      temp = + temp key// shift lowercase letters
      if > temp 'z' {
        temp = - temp 26ub
      } ;		
    } {
      if in temp uppers {
        temp = + temp key// shift uppercase letters
        if > temp 'Z' {
          temp = - temp 26ub
        } ;
      } ;//don't shift other characters
    }
    put_ubyte$ + message index temp
  }
}
function void caesar_decode(message:ptr key:uint) {
  caesar_encode$ message - 26u key
}
 
key = 1u
response = malloc$ 256u
puts$ "plaintext: "
getline$ response
caesar_encode$ response key
puts$ "cyphertext: "
puts$ response
putln$
caesar_decode$ response key
puts$ "decoded: "
puts$ response
free$ response
free$ lowers // ranges are objects and must be freed
free$ uppers
 
//this compiles with only 6 warnings!
 