

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


 
	str = "IT WAS THE BEST OF TIMES, IT WAS THE WORST OF TIMES."
 
	Wscript.Echo str
	Wscript.Echo Rotate(str,5)
	Wscript.Echo Rotate(Rotate(str,5),-5)
 
	'Rotate (Caesar encrypt/decrypt) test <numpos> positions.
	'  numpos < 0 - rotate left
	'  numpos > 0 - rotate right
	'Left rotation is converted to equivalent right rotation

	Function Rotate (text, numpos)
 
		dim dic: set dic = CreateObject("Scripting.Dictionary")
		dim ltr: ltr = Split("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z")
		dim rot: rot = (26 + numpos Mod 26) Mod 26 'convert all to right rotation
		dim ch
		dim i
 
		for i = 0 to ubound(ltr)
			dic(ltr(i)) = ltr((rot+i) Mod 26)
		next
 
		Rotate = ""
 
		for i = 1 to Len(text)
			ch = Mid(text,i,1)
			if dic.Exists(ch) Then
				Rotate = Rotate & dic(ch)
			else
				Rotate = Rotate & ch
			end if
		next
 
	End Function
 