

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


 
# Project : Caesar cipher
 
cipher = "pack my box with five dozen liquor jugs"
abc = "abcdefghijklmnopqrstuvwxyz"
see "text is to be encrypted:" + nl
see cipher+ nl + nl
str = ""
key = random(24) + 1
see "key = " + key + nl + nl
see "encrypted:" + nl
caesarencode(cipher, key)
see str + nl + nl
cipher = str
see "decrypted again:" + nl
caesardecode(cipher, key)
see str + nl
 
func caesarencode(cipher, key)
       str = ""
       for n = 1 to len(cipher)
            if cipher[n] != " "
               pos = substr(abc, cipher[n])
               if pos + key < len(abc)
                  str = str + abc[pos + key]
               else
                  if (pos+key)-len(abc) != 0
                     str = str + abc[(pos+key)%len(abc)]
                  else
                      str = str +abc[key+pos]
                  ok
                    ok 
               else
                  str = str + " "
               ok
       next
     return str
 
func caesardecode(cipher, key)
       str = ""
       for n= 1 to len(cipher)
            if cipher[n] != " "
               pos = substr(abc, cipher[n])
               if (pos - key) > 0 and pos != key
                   str = str + abc[pos - key]
                   loop
               else 
                   if pos = key
                      str = str + char(122)
                   else
                     str = str + abc[len(abc)-(key-pos)]
                   ok                     
               ok                
            else
               str = str + " "
            ok
       next
       return str
 