gpt4 book ai didi

java - Vigenere 解密奇数

转载 作者:行者123 更新时间:2023-11-29 03:36:49 27 4
gpt4 key购买 nike

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

例如,如果明文为“k”且 key 为“y”,则它会正确生成密文“i”((10 + 24 = 34 % 26 = 8))

然而,当解密密文是“i”并且 key 是“y”时,我得到((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);
}
}

最佳答案

注意Java中的取余运算符是这样定义的,结果的量级总是小于被除数的量级,如果被除数为负数,取余运算的结果为负数 [JLS] .

您可以通过执行以下操作获得所需的输出:

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

如果 positionP-positionK 为正,加法不会改变结果(因为 26%26=0)。如果 positionP-positionK 为负(介于 -25 和 0 之间),则 positionP - positionK + 26 将为非负,从而产生正确的结果。

关于java - Vigenere 解密奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15055052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com