

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


Procedure.s CC_encrypt(plainText.s, key, reverse = 0)
  ;if reverse <> 0 then reverse the encryption (decrypt)
  If reverse: reverse = 26: key = 26 - key: EndIf
 
  Static alphabet$ = "ABCEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
 
  Protected result.s, i, length = Len(plainText), letter.s, legal
  If key < 1 Or key > 25: ProcedureReturn: EndIf  ;keep key in range
 
  For i = 1 To length
    letter = Mid(plainText, i, 1)
    legal = FindString(alphabet$, letter, 1 + reverse)
    If legal
      result + Mid(alphabet$, legal + key, 1)
    Else
      result + letter
    EndIf 
  Next 
  ProcedureReturn result
EndProcedure
 
Procedure.s CC_decrypt(cypherText.s, key)
  ProcedureReturn CC_encrypt(cypherText, key, 1)
EndProcedure
 
If OpenConsole()
  Define key, plainText.s, encryptedText.s, decryptedText.s
 
  key = Random(24) + 1 ;get a random key in the range 1 -> 25
 
  plainText = "The quick brown fox jumped over the lazy dogs.": PrintN(RSet("Plain text = ", 17) + #DQUOTE$ + plainText + #DQUOTE$)
  encryptedText = CC_encrypt(plainText, key): PrintN(RSet("Encrypted text = ", 17) + #DQUOTE$ + encryptedText + #DQUOTE$)
  decryptedText = CC_decrypt(encryptedText, key): PrintN(RSet("Decrypted text = ", 17) + #DQUOTE$ + decryptedText + #DQUOTE$)
 
  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf