

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


1 rem caesar cipher
2 rem rosetta code
10 print chr$(147);chr$(14);
15 input "Enter a key value from 1 to 25";kv
20 if kv<1 or kv>25 then print "Out of range.":goto 15
25 gosub 1000
30 print chr$(147);"Enter a message to translate."
35 print:print "Press CTRL-Z when finished.":print
40 mg$="":gosub 2000
45 print chr$(147);"Processing...":gosub 3000
50 print chr$(147);"The translated message is:"
55 print:print cm$
100 print:print "Do another one? ";
110 get k$:if k$<>"y" and k$<>"n" then 110
120 print k$:if k$="y" then goto 10
130 end
 
1000 rem generate encoding table
1010 ec$=""
1015 rem lower case
1020 for i=kv to 26:ec$=ec$+chr$(i+64):next i
1021 for i=1 to kv-1:ec$=ec$+chr$(i+64):next i
1025 rem upper case
1030 for i=kv to 26:ec$=ec$+chr$(i+192):next i
1031 for i=1 to kv-1:ec$=ec$+chr$(i+192):next i
1099 return
 
2000 rem get user input routine
2005 print chr$(18);" ";chr$(146);chr$(157);
2010 get k$:if k$="" then 2010
2012 if k$=chr$(13) then print " ";chr$(157);
2015 print k$;
2020 if k$=chr$(20) then mg$=left$(mg$,len(mg$)-1):goto 2040
2025 if len(mg$)=255 or k$=chr$(26) then return
2030 mg$=mg$+k$
2040 goto 2005
 
3000 rem translate message
3005 cm$=""
3010 for i=1 to len(mg$)
3015 c=asc(mid$(mg$,i,1))
3020 if c<65 or (c>90 and c<193) or c>218 then cm$=cm$+chr$(c):goto 3030
3025 if c>=65 and c<=90 then c=c-64
3030 if c>=193 and c<=218 then c=(c-192)+26
3035 cm$=cm$+mid$(ec$,c,1)
3040 next i
3050 return