java中的解密(caesarCipher)错误结果
我编写了简单的凯撒密码算法,加密工作完美,但是当我想解密单词时,我得到了错误的结果。例如,密钥为 15 的“PQRO”应该是“ABCZ”,但我得到 “ABCB”。
public static void decrypt(String text, int k) {
char[] tAlf = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char[] tChar = text.toCharArray();
for (int i = 0; i < tChar.length; i++) {
for (int j = 0; j < tAlf.length; j++) {
if (text.charAt(i) == tAlf[j]) {
System.out.print(tAlf[(Math.abs(j-k)) % 26]);
}
}
}
}
看起来算法无法在字母表中倒退到“Z”。
I have written simple Caesar ciper algorithm, encrypting works perfectly, but when I want to decrypt word, I am getting wrong result. For example "PQRO" with key 15, should be "ABCZ", but I'm getting
"ABCB".
public static void decrypt(String text, int k) {
char[] tAlf = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
char[] tChar = text.toCharArray();
for (int i = 0; i < tChar.length; i++) {
for (int j = 0; j < tAlf.length; j++) {
if (text.charAt(i) == tAlf[j]) {
System.out.print(tAlf[(Math.abs(j-k)) % 26]);
}
}
}
}
It looks like algorithm can't get backward in alphabet to 'Z'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的技巧是理解数学运算。
首先,
%
不是取模运算,而是求余运算,这意味着结果可能为负数。abs
将从负值中创建正值。但这与用负值抵消问题不同,因为它会将 -1 映射到 1 而不是 25。因此,您可以做的是创建一个实际的模运算。在 Java 中,这
应该可以解决您的问题。
至于调试,您应该始终从将事物分成更小的部分开始。将
Math.abs(jk)) % 26
从数组索引中取出,并将其分配给例如整数newIndex
变量,这样您就可以实际看到中间结果。更好的是:尝试创建单独的方法,例如int charToIndex(char c)
和char indexToChar(int i)
,以便您可以单独测试它们。The trick here is to understand the math operations.
First of all,
%
is not the modulo operation, it is the remainder operation, which means that the result may be negative.abs
will create a positive value out of a negative value. But that's not the same as counteracting the problem with the negative value, as it would map e.g. -1 to 1 instead of 25.So what you can do is to create an actual modulo operation. In Java that is:
which should fix your problem.
As for debugging, you should always start by moving things into smaller pieces. Bring
Math.abs(j-k)) % 26
out of the array indexation and assign it to e.g. an integernewIndex
variable, so you can actually see the intermediate results. Even better: try and create separate methods such asint charToIndex(char c)
andchar indexToChar(int i)
so you can test them separately.