2013-02-24 68 views
1

我写了一个Java程序,用Vigenere密码进行编码的加密工作正常,但解密不适用于一些特殊情况。Vigenere解密奇怪

例如,如果解密时明文是数 'k',密钥为 'y' 的它正确地产生密文的 'i'((10 + 24 = 34%26 = 8))

然而((8-24)= -16%26 = -16)),即使它是正值,也是Q.当它应该正确地解密回''时, k'这将是10.

任何人都可以帮助我吗?如果需要,我可以发布更多代码。

---链接到维基Viginare加密算法http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher ---

 //decryption 
    else{ 
     for (int i=0; i < a.length(); i++){ 

       for (int j=0; j < full.length(); j++){ 
        //finding the index of the current cipher text letter 
        if (a.charAt(i) == full.charAt(j)){ 
         positionP = j; 

        } 
        //finding the index of the current key letter 
        if(key.charAt(i)==full.charAt(j)){ 
         positionK = j; 
        } 


       } 
       //using the formula for vigenere encoding it adds the newly encrypted character to the output 
       output = output + full.charAt((positionP - positionK)%26); 
      } 
     } 

回答

3

注意,在Java中的余运算符被定义为使得结果的幅度总是小于除数的幅度较小,如果分红为负数,剩余操作的结果为负数[JLS]

可在通过执行获得期望的输出:

output = output + full.charAt((positionP - positionK + 26)%26); 

positionP-positionK如果是肯定的,除了不改变的结果(因为26%26 = 0)。如果positionP-positionK为负值(介于-25和0之间),那么positionP - positionK + 26将为非负值,从而产生正确的结果。

+0

太谢谢你了!我真的被困住了,我发现好奇的是没有任何解密Vigenere的算法提到了这个!他们通常会说:(CipherTextIndex - keyTextIndex)%26 = IndexOfPlainText 我可能会在wiki中添加一条关于此的注释。 非常感谢你! – 2013-02-24 18:51:45

+0

@Luke它依赖于你如何定义负数的其余部分。见 http://stackoverflow.com/questions/4403542/how-does-java-do-modulus-calculations-with-negative-numbers – Javier 2013-02-24 18:58:09

1

如果你的密钥是'y'= 24,你的字母表的长度是26,你必须将字母键= 26 - 24 = 2进行解密。你总是要添加,然后计算国防部26

所以,你的代码必须是

 //decryption 
else{ 
    for (int i=0; i < a.length(); i++){ 

      for (int j=0; j < full.length(); j++){ 
       //finding the index of the current cipher text letter 
       if (a.charAt(i) == full.charAt(j)){ 
        positionP = j; 

       } 
       //finding the index of the current key letter 
       if(key.charAt(i)==full.charAt(j)){ 
        positionK = j; 
       } 


      } 
      //using the formula for vigenere encoding it adds the newly encrypted character to the output 
      output = output + full.charAt((positionP + (26-positionK))%26); 
     } 
    }