A Caesar cipher shifts letters in a string
. In this cipher, each letter is shifted a certain number of places in the alphabet.
In this cipher, if the letter overflows after shifting, it begins again at the letter "a". This cipher is similar to ROT13.
The Caesar method receives a string
value and an int
that indicates the shift. In the method, we convert the string
to a char
array with ToCharArray
.
string
, 18) can be reversed with a call to Caesar(string
, -18).string
, -4).using System; class Program { /// <summary> /// Apply Caesar cipher with shift. /// </summary> static string Caesar(string value, int shift) { char[] buffer = value.ToCharArray(); for (int i = 0; i < buffer.Length; i++) { // Letter. char letter = buffer[i]; // Add shift to all. letter = (char)(letter + shift); // Subtract 26 if past z. // ... Add 26 if below a. if (letter > 'z') { letter = (char)(letter - 26); } else if (letter < 'a') { letter = (char)(letter + 26); } // Store. buffer[i] = letter; } return new string(buffer); } static void Main() { string a = "test"; string b = Caesar(a, 18); // Ok string c = Caesar(b, -18); // Ok string d = Caesar(a, 1); // Ok string e = Caesar(d, -1); // Ok string f = "exxegoexsrgi"; string g = Caesar(f, -4); // Ok Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); Console.WriteLine(e); Console.WriteLine(f); Console.WriteLine(g); } }test lwkl test uftu test exxegoexsrgi attackatonce
What happens with non-letter characters in the cipher? The cipher does not specify how numbers should be treated. It would be simple to ignore them.
The Caesar cipher is a substitution cipher that shifts letter positions. It is similar to ROT13. The shift value can be kept secret to make the cipher harder to break
.
This sort of cipher will not provide any real security. You could use the Caesar cipher and then an actual encryption algorithm on top of that.