解密Java中的Vigenère密码

问题描述 投票:2回答: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();
}
java encryption vigenere
2个回答
0
投票
shiftedPos += alphabetSize;

你为什么这样做?我认为只有在shiftedPos <0时才必须这样做。

if(shiftedPos<0)
   shiftedPos += alphabetSize;

那是因为如果a = 0且b = 1,则(a-b)= - 1表示z。要使用整个ASCII集,您只需要以正确的顺序将所有ASCII字符替换为alpabeth字符串和大小。


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对其进行修改,以获得正确的值。

在处理命名约定时要小心。这确实会引起一些问题......

除此之外,我认为你的代码实际上是正常的。我当然看不出任何问题。通过online encryptor/decryptor尝试一下。

© www.soinside.com 2019 - 2024. All rights reserved.