Java实现凯撒密码的加密和解密

加密

public class CaeSar {
    private static char[] CAPITAL_LETTERS = new char[] {'A','B','C','D',
            'E','F','G','H','I','J','K','L', 'M','N','O','P','Q','R','S',
            'T','U','V','W','X','Y','Z'};

    private static char[] SMALL_LETTERS = new char[] {'a','b','c','d','e',
            'f','g','h','i','j','k','l', 'm','n','o','p','q','r','s','t',
            'u','v','w','x','y','z'};
    private static int KEY = 3;
    private static int MOD = 26;

    public static void caesarCipher() {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String s = sc.nextLine();
            StringBuilder caeCipher = new StringBuilder();
            int[] caeIndex = new int[s.length()];
            for (int i = 0; i < s.length(); i++) {
                char letter = s.charAt(i);


                //如果letter是大写字母就在CAPITAL_LETTERS中寻找letter的位置
                if (letter >= 'A' && letter <= 'Z') {
                    for (int j = 0; j < CAPITAL_LETTERS.length; j++) {
                        if (CAPITAL_LETTERS[j] == letter) {
                            //根据index找出加密后对应的位置
                            j = Math.floorMod(j + KEY , MOD);
                            caeCipher.append(CAPITAL_LETTERS[j]);
                            caeIndex[i] = j;
                            break;
                        }
                    }
                } else {
                    //如果letter是小写字母就在SMALL_LETTERS中寻找letter的位置
                    for (int j = 0; j < SMALL_LETTERS.length; j++) {
                        if (SMALL_LETTERS[j] == letter) {
                            //根据index找出加密后对应的位置
                            j = Math.floorMod(j + KEY , MOD);
                            caeCipher.append(SMALL_LETTERS[j]);
                            caeIndex[i] = j;
                            break;
                        }
                    }
                }
            }
            System.out.println(caeCipher.toString());
            System.out.println(Arrays.toString(caeIndex));
        }
    }

    public static void main(String[] args) {
        caesarCipher();
    }
}

解密只需要将 “j = Math.floorMod(j + KEY , MOD);”
修改为 “j = Math.floorMod(j - KEY , MOD);” 即可。

发布了42 篇原创文章 · 获赞 35 · 访问量 2093

猜你喜欢

转载自blog.csdn.net/weixin_44780625/article/details/104636797