我的程序能够加密一条消息,但我不确定如何破译使其无法正常工作

时间:2015-02-27 05:00:35

标签: java

解密是解决问题的原因。

public static void encrypt(Scanner scan, PrintWriter out, String key) throws IOException {
        while(scan.hasNextLine()){
            String lineRead = scan.nextLine();

            for(int i=0; i < lineRead.length(); i++){
                char c = lineRead.charAt(i);
                out.print(shiftUpByK(c, key.charAt(i%key.length()) - 'a' ));
            }
        out.println();

    }
}

public static void decrypt(Scanner scan, PrintWriter out, String key) {
    while(scan.hasNextLine()){
        String lineRead = scan.nextLine();

        for(int i = 0; i < lineRead.length(); i++){
            char c = lineRead.charAt(i);
            out.print(shiftDownByK(c,key.charAt(i%key.length())));
        }
        out.println();
    }

}

public static final int NUM_LETTERS = 26;

public static char shiftUpByK(char c, int k) {
    if ('a' <= c && c <= 'z')
        return (char) ('a' + (c - 'a' + k) % NUM_LETTERS);
    if ('A' <= c && c <= 'Z')
        return (char) ('A' + (c - 'A' + k) % NUM_LETTERS);
    return c; // don't encrypt if not an alphabetic character
}

public static char shiftDownByK(char c, int k) {
    return shiftUpByK(c, NUM_LETTERS - k);
}

0 个答案:

没有答案