仿射密码解密

时间:2015-01-24 08:00:13

标签: java encryption

我觉得我的数学和逻辑是正确的,我不确定我做错了什么。我尝试了几个不同的b值,没有任何作用。出于某种原因,无论使用常数,“f”总是变为“v”而“k”总是变为“q”。我的输出是:glqvafkpuzejotydinsxchmrwb,abcdwvghijqlmnolqrstgvwxyb。当b = 0时,解密方法有效。

public class Asgn2No2CodeDecode {


    public static void main(String[] args) {


        System.out.println(affineCipher("abcdefghijklmnopqrstuvwxyz"));

        System.out.println(affineDecipher(affineCipher("abcdefghijklmnopqrstuvwxyz"))); 

    }
    public static String affineCipher(String plainTxt)
    {

        StringBuilder cipherTxt = new StringBuilder();

        String alphabet = "abcdefghijklmnopqrstuvwxyz";

        int a = 5;
        int b = 6;
        int charNum = 0;

        char alphChar;
        char ciphChar;

        for (int i = 0; i < plainTxt.length(); i++)
        {
            ciphChar = plainTxt.charAt(i);

            if (Character.isLetter(ciphChar))
           {
               for (int j = 0; j<alphabet.length(); j++)
               {
                   alphChar = alphabet.charAt(j);

                   if (ciphChar == alphChar)
                   {
                       charNum = ((a*j + b)%26);

                   }//end if

               }//end for alph

               cipherTxt.append(alphabet.charAt(charNum));

           }else cipherTxt.append(plainTxt.charAt(i));
        }//end for plain
        return cipherTxt.toString();
    }//end affineCipher(String)
    public static String affineDecipher(String cipherTxt)
    {

        StringBuilder plainTxt = new StringBuilder();

        String alphabet = "abcdefghijklmnopqrstuvwxyz";
        int aInv = 21;
        int b = 6;
        int charNum = 0;

        char alphChar;
        char ciphChar;

        for (int i = 0; i < cipherTxt.length(); i++)
        {
            ciphChar = cipherTxt.charAt(i);

            if (Character.isLetter(ciphChar))
           {
               for (int x = 0; x<alphabet.length(); x++)
               {
                   alphChar = alphabet.charAt(x);

                   if (ciphChar == alphChar)
                   {
                       if (x>=b)
                       { 
                       charNum = (((aInv*(x-b))%26));
                       }
                       else charNum = (-((aInv*(x-b))%26));

                   }//end if

               }//end for alph

               plainTxt.append(alphabet.charAt(charNum));

           }else plainTxt.append(cipherTxt.charAt(i));
        }//end for plain
        return plainTxt.toString();
    }//end affineCipher(String)


}

0 个答案:

没有答案