[英]Case sensitive Vigenere cipher produces wrong output
我已經投入了大量精力使密碼更加健壯,因此輸出區分大小寫。
意思是,如果大寫字母在消息字符串中,則輸出將在該位置的字符串中具有編碼的大寫字母。例如, InpUT MesSagE
變為HrhTS WwlReyD
。 使用的關鍵是test
。
public String encrypt(String text, final String key) {
int a_num = (int) 'a';
int A_num = (int) 'A';
String output = "";
for (int i = 0, j = 0; i < text.length(); i++) {
int cur = (int) text.charAt(i);
// check for spaces
if (text.charAt(i) == ' ') {
output += " ";
// check for lowercase
} else if (cur >= 'a' && cur < 'z' + 26) {
output += Character.toString((char) ((cur + key.charAt(j) - 2 * 'a') % 26 + 'a'));
j = ++j % key.length();
// check for uppercase between 'N' and 'Z'
} else if (cur >= 'N' && cur < 'Z') {
output += Character.toString((char) ((cur + key.charAt(j) - 2 * 'A') % 26 + 'N' + 7));
j = ++j % key.length();
// check for uppercase between 'A' and 'M'
} else {
output += Character.toString((char) ((cur + key.charAt(j) - 2 * 'A') % 26 + 'A' - 6));
j = ++j % key.length();
}
}
return output;
}
目前,所有小寫字母似乎都是正確的,而一些大寫字母也是如此。 我的問題有時是大寫錯誤,例如由於我的數學/邏輯不正確,符號將成為輸出的一部分。
我非常肯定的變量是代碼的這些部分:
((cur + key.charAt(j) - 2 * 'A') % 26 + 'A' - 6));
public String encrypt(String text, final String key) {
// we assume the key is all lower case
// and only inputs are letters and space (could enhance to leave all else alone)
int a_num = (int) 'a'; //unused?
int A_num = (int) 'A';//unused?
String output = "";
for (int i = 0, j = 0; i < text.length(); i++) {
int cur = (int) text.charAt(i);
// check for spaces
if (text.charAt(i) == ' ') {
output += " ";
}
// check for lowercase
else if (cur >= 'a' && cur <= 'z') {
output += Character.toString((char) ((cur + key.charAt(j) - 2 * 'a') % 26 + 'a'));
j = ++j % key.length();
}
// should work for uppercase between 'A' and 'Z'
else {
output += Character.toString((char) ((cur -'A' + key.charAt(j) - 'a') % 26 + 'A'));
j = ++j % key.length();
}
}
return output;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.