I have implemented the Caesar Cipher algorithm in Java 8.
The Problem
Heute ist Freitag.
results into this encoded text using 22 as a key:
^{
{6
6{
w}D
Decoding this again gets me this output:
Heu
e is
Frei
ag.
The Code and description
It should be noted that my algorithm doesn't care about characters like '\n', meaning some characters might be translated to escape sequences or spaces etc. This is also totally what I want to happen, thought it doesn't work.
public String encode(String txt, int key) {
if(key <= 0)
return txt;
String result = "";
for (int i = 0; i < txt.length(); i++) {
int x = (txt.charAt(i) + key) % 128;
result += (char) x;
}
System.out.println(result);
return result;
}
public String decipherM(String txt, int key) {
if(key <= 0)
return txt;
String result = "";
for (int i = 0; i < txt.length(); i++) {
int x = (txt.charAt(i) - key) % 128;
if(x < 0)
x += 128;
result += (char) x;
}
System.out.println(result);
return result;
}
The question
I would really like to know why it doesn't work with escape sequences or other non alphabetic characters.