C# Caesar Cipher

Char type

A Caesar cipher shifts letters in a string. In this cipher, each letter is shifted a certain number of places in the alphabet. If the letter overflows, it begins again at the letter 'a'.

Caesar method

Note

In the Caesar method, we convert the string to a char array with ToCharArray. Next, we apply the shift value to every character. If the character goes above 'z', we shift it back 26 places. If the character goes below 'a', we shift it forward 26 places. This is correct for all lowercase letters.

ToCharArray

This C# example program implements a Caesar cipher using a static method.

Program that implements Caesar cipher [C#]

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 on overflow.
	    // Add 26 on underflow.
	    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);
    }
}

Output

test
lwkl
test
uftu
test
exxegoexsrgi
attackatonce

Result. We can see that this cipher is reversible; a call to Caesar(string, 18) can be reversed with a call to Caesar(string, -18). Also, the example from Wikipedia can be solved with a call to Caesar(string, -4).

Caesar cipherQuestion and answer

Numeric characters. What happens with numeric (or non-letter) characters in the cipher? The Wikipedia article does not specify how numbers should be treated. It would be simple to ignore them. Another option would be to throw an exception if a number is found.

Summary

The Caesar cipher is a substitution cipher that shifts letter positions. It is very similar to the ROT13 cipher. One benefit to this cipher is the shift value can be kept secret to improve security slightly. This sort of cipher will not prevent any determined hackers from unencrypting your data, unless you use the Caesar cipher and then a good encryption algorithm on top of that.

Algorithms
.NET