

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


100 PROGRAM "CaesarCi.bas"
110 STRING M$*254
120 INPUT PROMPT "String: ":M$
130 DO
140   INPUT PROMPT "Key (1-25): ":KEY
150 LOOP UNTIL KEY>0 AND KEY<26
160 PRINT "Original message:  ";M$
170 CALL ENCRYPT(M$,KEY)
180 PRINT "Encrypted message: ";M$
190 CALL DECRYPT(M$,KEY)
200 PRINT "Decrypted message: ";M$
210 DEF ENCRYPT(REF M$,KEY)
220   STRING T$*254
230   LET T$=""
240   FOR I=1 TO LEN(M$)
250     SELECT CASE M$(I)
260     CASE "A" TO "Z"
270       LET T$=T$&CHR$(65+MOD(ORD(M$(I))-65+KEY,26))
280     CASE "a" TO "z"
290       LET T$=T$&CHR$(97+MOD(ORD(M$(I))-97+KEY,26))
300     CASE ELSE
310       LET T$=T$&M$(I)
320     END SELECT
330   NEXT
340   LET M$=T$
350 END DEF
360 DEF DECRYPT(REF M$,KEY)
370   STRING T$*254
380   LET T$=""
390   FOR I=1 TO LEN(M$)
400     SELECT CASE M$(I)
410     CASE "A" TO "Z"
420       LET T$=T$&CHR$(65+MOD(ORD(M$(I))-39-KEY,26))
430     CASE "a" TO "z"
440       LET T$=T$&CHR$(97+MOD(ORD(M$(I))-71-KEY,26))
450     CASE ELSE
460       LET T$=T$&M$(I)
470     END SELECT
480   NEXT
490   LET M$=T$
500 END DEF