仿射密码:解密文本与纯文本不匹配

时间:2015-10-31 23:24:23

标签: java encryption

这是我的仿射加密和解密代码。

我有char个26个字符的数组。

生成的密文
ax + b % 26

与解密公式

不匹配
a - inverse(ciphertext[c]-b) % 26

例如,当a=3b=5时,我加密rr在字符数组中的位置是17加密公式:

((3*17+5) %26) = (56%26) = 4

数组中4位置的字符为e。当我解密密文时,3的反向值为9。所以,Math.abs(3(4-5)%26)=3不正确。

private static String affinecipher(String plainText) {
    String encrypt = "";
    int value = 0;
    int location=0;
    String text=plainText.toUpperCase();
    Scanner inputData = new Scanner(System.in);
    System.out.print("Enter a:");
    a = inputData.nextInt();
    System.out.print("Enter b:");
    b = inputData.nextInt();
    for(int p = 0; p < text.length(); p++){        
        for(int q =0 ; q<letter.length; q++){                  
            if(text.charAt(p)==letter[q]){
                // checking each plaintext character position to letter array position.
                // if match found returning the letter position
                location=q;                         
            }
        }
        value= (((a*location)+b) % m);

        // value of a multiplied by letter position adding to b and taking the mod.
        // adding the string with value position from letter           
        encrypt = encrypt +letter[value];
    }
    return encrypt;
}


//decryption
private static String decryptAffineCipher(String encryptText){
    String decrypt=" ";int location=0;

    //calculating the inverse value
    a %= 26;
    for(int x = 1; x < 26; x++) {
        if((a*x) % 26 == 1) {
            inverse=x;
        }
    }

    for (int p = 0; p < encryptText.length(); p++){
        for(int q =0 ; q<letter.length; q++){ 
            //finding the location of cipher character
            if(encryptText.charAt(p)==letter[q]){
                location=q;                           
            } 
        }

        //decryption formula a-inverse(c-b)%26
        int step1=Math.abs(location-b);
        int step2=inverse* step1;
        int value=step2 %26;

        //char letter[26] that stores value from A to Z
        decrypt = decrypt +letter[value];
    }
    return decrypt;
}

0 个答案:

没有答案