C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Shift: If the character goes above "z", we shift it back 26 places. If the character goes below "a", we shift it forward 26 places.
So: We apply the shift value to every character. This is correct for all lowercase letters.
CharInfo: 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 cipher: WikipediaC# program that implements Caesar cipher
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
Also: Another option would be to throw an exception if a number is found. Callers of Caesar would have to be prepared for this.
ExceptionNote: This sort of cipher will not prevent any determined hackers from unencrypting your data.
However: You could use the Caesar cipher and then an actual encryption algorithm on top of that.