Java中的随机替换密码

时间:2015-01-03 22:48:52

标签: java encryption

我目前正在创建使用预定义字符在Java中加密文本的代码。代码首先对文本进行加密并将其打印出来,然后对其进行解密并打印出原始句子。当我单独打印字母时,它可以工作但是当我将字母与空格键组合时它不起作用。我得到的错误是

  

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:27

     

at cipher.cipher.decrypt(cipher.java:70)

     

at cipher.cipher.main(cipher.java:24)

public static final int ASCII_SUB = 96;
public static final int ASCII_SUB_FOR_SPACE = 32;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Enter the text that you would like to cipher:");
    Scanner input = new Scanner(System.in);
    String cipher = input.nextLine();
    input.close();

    int length = cipher.length();

    char encryption[] = createCipher();
    String cipheredText = encrypt(encryption, cipher, length);

    System.out.println("The encrypted version of your sentence is: " + cipheredText);
    char[] encryptedCharacters = cipheredText.toCharArray();
    String original = decrypt(encryption, encryptedCharacters, length);

    System.out.println("Your original sentence was: " + original);
}

public static char[] createCipher(){

    char[] encryption = {'p', 'u', 'y', 'k', 'h', 'q', 'j', 'l',
            'i', 'd', 'v', 'b', ' ', 'o', 'c', 'f', 'r', 'e', 't', 'x',
            'a', 'n', 'z', 'm', 'g', 'w', 's' };

    return encryption;
}


public static String encrypt(char[] encryption, String cipher, int length){

    String lowercaseCipher = cipher.toLowerCase();
    char[] characterArray = lowercaseCipher.toCharArray();

    for(int i = 0; i<length; i++){
        if(characterArray[i] == ' '){
            characterArray[i] = (char) (characterArray[i] - ASCII_SUB_FOR_SPACE);
        }
        else{
            characterArray[i] = (char) (characterArray[i] - ASCII_SUB);
        }
    }

    for(int i = 0; i<length; i++){
        characterArray[i] = encryption[characterArray[i]];
    }

    String cipheredText = new String(characterArray);
    return cipheredText;
}


public static String decrypt(char[] encryption, char[] encryptedCharacters, int length){

    int p = 0;
    int i = 0;
    int w = 0;
    int[] deciphered = new int[length];

    do {
        if(encryption[i] == encryptedCharacters[p]){
            deciphered[w] = i;
            i = 0;
            w++;
            p++;
            }
    i++;
    }while(p<length);

    char[] finishedSentence = new char[length];
    for(int x = 0;x<length;x++){
        if(deciphered[x] == 0){
            finishedSentence[x] = (char) (deciphered[x] + ASCII_SUB_FOR_SPACE);
        }
        else{
            finishedSentence[x] = (char) (deciphered[x] + ASCII_SUB);
        }
    }   


    String deCipheredText = new String(finishedSentence);

    return deCipheredText;
}

第70行是:if(encryption [i] == encryptedCharacters [p]){

P.S。为可怜的变量名称道歉,但我还没有时间修复它们。

1 个答案:

答案 0 :(得分:0)

使用第70行的if语句。“i”将始终从1开始而不是0,将后增量放入else循环并修复此问题。