I put together a cipher code for my computer science class and my encryption and decryption works for capital case letters, but not for lowercase. For example, "Dog" is suppose to encrypt to "Eph". Instead I get "Ebt". "DOG" encrypts just fine.
Here is my code:
public class Cipher {
private int secretKey;
public Cipher() {
secretKey = 1;
String s = "A B C";
String b = caesarEncrypt(s);
String c = caesarDecrypt(b);
System.out.println("Encrypted: " + b);
System.out.println("Decrypted: " + c);
}
public String caesarEncrypt(String s) {
String r = "";
for(int i = 0; i < s.length(); i++){
char c = (char)(s.charAt(i));
if(Character.isLetter(c)){
if(Character.isUpperCase(c))
r += (char)('A' + (c + 'A' + secretKey) % 26);
else
r += (char)('a' + (c + 'a' + secretKey) % 26);
} else
r += c;
}
return r;
}
public String caesarDecrypt(String s) {
String r = "";
for(int i = 0; i < s.length(); i++) {
char c = (char)(s.charAt(i));
if(Character.isLetter(c)) {
if(Character.isUpperCase(c))
r += (char)('A' + (c - 'A' + (26 - secretKey)) % 26);
else
r += (char)('a' + (c - 'a' + (26 - secretKey)) % 26);
} else r+= c;
}
return r;
}
}
Edit: The forumulas have different + and - signs. I'll leave the code as it is so everyone is on the same page. Sorry.
I find a problem in both the encryption algorithms in caesarEncrypt. Replace the + after c with a -
if(Character.isLetter(c)){
if(Character.isUpperCase(c))
r += (char)('A' + (c - 'A' + secretKey) % 26);
else
r += (char)('a' + (c - 'a' + secretKey) % 26);