

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


 
Option Explicit
 
Sub Main_Caesar()
Dim ch As String
    ch = Caesar_Cipher("CAESAR: Who is it in the press that calls on me? I hear a tongue, shriller than all the music, Cry 'Caesar!' Speak; Caesar is turn'd to hear.", 14)
    Debug.Print ch
    Debug.Print Caesar_Cipher(ch, -14)
End Sub
 
Function Caesar_Cipher(sText As String, lngNumber As Long) As String
Dim Tbl, strGlob As String, strTemp As String, i As Long, bytAscii As Byte
  Const MAJ As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Const NB_LETTERS As Byte = 26
      Const DIFFASCIIMAJ As Byte = 65 - NB_LETTERS
        Const DIFFASCIIMIN As Byte = 97 - NB_LETTERS
 
    strTemp = sText
    If lngNumber < NB_LETTERS And lngNumber > NB_LETTERS * -1 Then
        strGlob = String(NB_LETTERS * 4, " ")
        LSet strGlob = MAJ & MAJ & MAJ
        Tbl = Split(StrConv(strGlob, vbUnicode), Chr(0))
        For i = 1 To Len(strTemp)
            If Mid(strTemp, i, 1) Like "[a-zA-Z]" Then
                bytAscii = Asc(Mid(strTemp, i, 1))
                If Mid(strTemp, i, 1) = Tbl(bytAscii - DIFFASCIIMAJ) Then
                    Mid(strTemp, i) = Tbl(bytAscii - DIFFASCIIMAJ + lngNumber)
                Else
                    Mid(strTemp, i) = LCase(Tbl(bytAscii - DIFFASCIIMIN + lngNumber))
                End If
            End If
        Next i
    End If
    Caesar_Cipher = strTemp
End Function
 