

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


Public Sub Main()
Dim byKey As Byte = 3                                                                 'The key (Enter 26 to get the same output as input)
Dim byCount As Byte                                                                   'Counter
Dim sCeasar As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"        'Used to calculate the cipher
Dim sString As String = "The five boxing wizards jump quickly"                        'Phrase to encrypt
Dim sCoded, sTemp As String                                                           'Various strings
 
For byCount = 1 To Len(sString)                                                       'Count through each letter in the phrase
  If Mid(sString, byCount, 1) = " " Then                                              'If it's a space..
    sCoded &= " "                                                                     'Keep it a space
    Continue                                                                          'Jump to the next iteration of the loop
  Endif
  sTemp = Mid(sCeasar, InStr(sCeasar, Mid(UCase(sString), byCount, 1)) + byKey, 1)    'Get the new 'coded' letter
  If Asc(Mid(sString, byCount, 1)) > 96 Then sTemp = Chr(Asc(sTemp) + 32)             'If the original was lower case then make the new 'coded' letter lower case
  sCoded &= sTemp                                                                     'Add the result to the code string
Next
 
Print sString & gb.NewLine & sCoded                                                   'Print the result
 
End