Java Ceasar Cipher环绕

时间:2018-04-03 14:45:51

标签: java encryption queue

我使用队列作为编码密钥使用java创建Ceasar密码,我已经完成了大部分代码但是我遇到了环绕式方法的问题,除此之外似乎一切都是细

如何修改我的环绕以使其正常工作?因为有了这个环绕,当我尝试在我的字符串消息中编码和解码时,我会得到符号

public class Cipher {

private static final String key = "4 13 -24 32 1 36 16 3";
private static GenericQueue<Integer> keyList;

public static String encode(String encoded) {
    return convertedMessage(1, encoded);
}

public static String decode(String decoded) {
    return convertedMessage(-1, decoded);
}

/**
 * Adds the the integers of the encoding key to the queue
 */
private static void listToQueue() {
    keyList = new GenericQueue<Integer>();
    Scanner keyValue = new Scanner(key);
    while(keyValue.hasNextInt()) {
        keyList.addToQueue(keyValue.nextInt());
    }
}

private static String convertedMessage(int sign, String encoded) {
    listToQueue();
    String output = "";

    for (int i = 0; i < encoded.length(); i++) {
        int keyInList = keyList.deleteFromQueue();
        keyList.addToQueue(keyInList); //adds back to the end of the list for wraparound
        if(Character.isLetter(encoded.charAt(i))) {
            output += encryption(encoded.charAt(i), keyInList * sign);
        }
        else {
            output += encoded.charAt(i);
        }
    }
    keyList.clearQueue();
    return output;
}

//NEED HELP WITH THIS METHOD@@@
private static String wraparound(char newChar, int shift) {
    int encryptedChar = (int) newChar + shift;
    if (Character.isUpperCase(newChar)) {
        if (encryptedChar < (int) 'A') {
            encryptedChar = (int) '[' + ((shift + ((int) newChar - (int) 'A')) % 26);
            if (encryptedChar == (int) '[') {
                encryptedChar = (int) 'A';
            }
        }
        else {
            if (encryptedChar > (int) 'Z') {
                encryptedChar = (int) '@' + ((encryptedChar - (int) 'Z') % 26);
                if (encryptedChar == (int) '@') {
                    newChar = (int) 'Z';
                }
            }
        }
    } //end of first if
    else {
        if (encryptedChar < (int) 'a') {
            encryptedChar = (int) '{' + ((shift + ((int) newChar - (int) 'a')) % 26);
            if (encryptedChar == (int) '{') {
                encryptedChar = (int) 'a';
            }
        }
        else {
            if (encryptedChar > (int) 'z') {
                encryptedChar = (int) '`' + ((newChar - (int) 'z') % 26);
                if (encryptedChar == (int) '`') {
                    encryptedChar = (int) 'z';
                }
            }
        }
    }//end of first else
    return Character.toString((char) (encryptedChar));
}

}

主要

    Cipher encrypt = new Cipher();
    String string = "This IS my message, to ENCODE";
    String encoded = encrypt.encode(string);
    System.out.println(encoded);
    String decoded = encrypt.decode(encoded);
    System.out.println(decoded);

输出:

Pgcz NQ ix taxqxcd,pt BJBIKA

这是我的混乱^ ge,到ENCODE

0 个答案:

没有答案