I just learn about cryptography few week ago. I want to develop my tool to encrypt and decrypt Caesar cipher. But when I decrypt, it alway return weird value. Example: if I encrypt "my first tool crypto", it not return right decrypt "zl svefg gbby pelcgb", but "m_ fiXYZ ZUUl cX_VZU" with rotate 13 or another rotate I chose.
string array1 = "zl svefg gbby pelcgb";
int t2 = 0;
foreach (char c in array1)
{
if ((int)c == 32 || ((int)c >= 48 && (int)c <= 57))
t2 = c;
else
t2 = ((((int)c - 97) - 13) % 26) + 97;
Console.Write((char)t2);
}
The problem is that when you do subtraction you get negative values. The modulo operator will then give wrong results. You need to always add to the value.
The proper way to do it is:
t2 = ((((int)c - 97) - 13 + 26) % 26) + 97;
This will make sure the values are always positive and the modulo works as you expect.