2

Java メソッドを使用して暗号化を解読しようとしていますが、コードが正しく返されないようです。暗号化プロセスを元に戻そうとしましたが、何が間違っているのかわかりません。申し訳ありませんが、これがばかげた質問でないことを願っています。

public void decrypt()
{
    String cipherText = this.message;
    String key = this.KEY;
    String alphabet = "abcdefghijklmnopqrstuvwxyz"; 
    int alphabetSize = alphabet.length();
    int textSize = cipherText.length();
    int keySize = key.length();
    StringBuilder decryptedText = new StringBuilder(textSize);

    for (int i = 0; i < textSize; i++)
    {
        char encyrptChar = cipherText.charAt(i); // get the current character to be shifted
        char keyChar = key.charAt(i % keySize); // use key again if the end is reached
        int plainPos = alphabet.indexOf(encyrptChar); // plain character's position in alphabet string
         // decrypt the input text
        int keyPos = alphabet.indexOf(keyChar); // key character's position in alphabet
        int shiftedPos = plainPos-keyPos;
        shiftedPos += alphabetSize;
        decryptedText.append(alphabet.charAt(shiftedPos));
    }

    this.message =  decryptedText.toString();
}
4

2 に答える 2

0

これらの行を取ります:

    char encyrptChar = cipherText.charAt(i); // get the current character to be shifted
    char keyChar = key.charAt(i % keySize); // use key again if the end is reached
    int plainPos = alphabet.indexOf(encyrptChar); // plain character's position in alphabet string

    int keyPos = alphabet.indexOf(keyChar); // key character's position in alphabet
            int shiftedPos = plainPos-keyPos;
            shiftedPos += alphabetSize;

いくつか問題があります。

  1. plainPos実際には暗号化された値です。混同しないでください。
  2. plainPos-keyPos復号化された値と等しくなければなりません。alphabetSize次に、正しい値を取得するために、それを modding する必要があります。

命名規則に取り組むときは注意してください。それは本当にいくつかの問題を引き起こす可能性があります...

それを除けば、あなたのコードは実際に正しく機能していると思います。確かに問題は見えません。オンラインの暗号化/復号化ツールで試してみてください。

于 2012-11-15T23:57:39.973 に答える
0
shiftedPos += alphabetSize;

なぜこれを行うのですか?shiftPos<0 の場合にのみこれを行う必要があると思います。

if(shiftedPos<0)
   shiftedPos += alphabetSize;

これは、a=0 かつ b=1 の場合、(ab)=-1 は z を意味するためです。ASCII セット全体を操作するには、アルファベット文字列とサイズを正しい順序ですべての ASCII 文字に置き換えるだけです。

于 2012-11-15T19:37:45.950 に答える