

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


key = 7
 
Print "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
 
'Encrypt the text
Print CaesarCypher$("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", key)
 
'Decrypt the text by changing the key to (26 - key)
Print CaesarCypher$(CaesarCypher$("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", key), (26 - key))
 
Function CaesarCypher$(string$, key)
    If (key < 0) Or (key > 25) Then _
    CaesarCypher$ = "Key is Ouside of Bounds" : Exit Function
    For i = 1 To Len(string$)
        rotate = Asc(Mid$(string$, i, 1))
        rotate = (rotate + key)
        If Asc(Mid$(string$, i, 1)) > Asc("Z") Then
            If rotate > Asc("z") Then rotate = (Asc("a") + (rotate - Asc("z")) - 1)
        Else
            If rotate > Asc("Z") Then rotate = (Asc("A") + (rotate - Asc("Z")) - 1)
        End If
        CaesarCypher$ = (CaesarCypher$ + Chr$(rotate))
    Next i
End Function