我为计算机科学类(class)编写了一个密码,并且我的加密和解密适用于大写字母,但不适用于小写字母。例如,“Dog”假设加密为“Eph”。相反,我得到“Ebt”。 “DOG”加密得很好。
这是我的代码:
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;
}
}
编辑:论坛有不同的 + 和 - 符号。我将保留代码原样,以便每个人都在同一页面上。抱歉。
最佳答案
我发现 caesarEncrypt 中的两种加密算法都有问题。 将 c 后面的 + 替换为 -
if(Character.isLetter(c)){
if(Character.isUpperCase(c))
r += (char)('A' + (c - 'A' + secretKey) % 26);
else
r += (char)('a' + (c - 'a' + secretKey) % 26);
关于java - 小写密码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35414571/