java - 小写密码错误

标签 java encryption caesar-cipher

我为计算机科学类(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/

相关文章:

java - 打印前人的 Dijkstra 算法

c# - 在 .NET 中使用 OpenSSL 加密和解密文件

ios - 在objective c中实现RC4加密和URL编码

JavaScript动态创建对象未定义

c - 在 C 中的凯撒密码中使用 argc 和 argv

java - 是否可以附加 2 个富文本字符串?

Java 转换接口(interface)但使用对象方法

C语言凯撒密码

java - 在 SWT 应用程序中使用 styledText

c++ - 如何将 c++ 变量安全地保存在 RAM 中?