我有一个文本文件,我已经使用移位加密,但我需要再次加密加密文本,但这次使用vigenere cipher。然后,我需要解密该加密文本(首先是vigenere然后移动),但所有大写和小写字母都需要保持相同,以及黑色空格,引号,逗号和句号。我已经完成了移位加密和解密所剩下的就是vigenere。下面显示的是我加密Vigenere的类,我还没有编写解密,因为我陷入了加密步骤。 谢谢。
public static String vigenereEncryption(String str,String keyword)
{
char [] c_arr = null;
int g =0;
int keyLength = keyword.length();
String encrypted = "";
String update ="";
String []list = null;
for(int k = 0; k<keyword.length();k++){
char key = keyword.charAt(k);
c_arr = keyword.toCharArray();
update = update + key;
}
for(int i=0;i<str.length();i++)
{
//stores ascii value of character in the string at index 'i'
int c=str.charAt(i);
//encryption logic for uppercase letters
if(Character.isUpperCase(c))
{
for(int k = 0; k<keyword.length();k++){
g = c_arr[k] ;
}
c=(c+g)%26;
//if c value exceeds the ascii value of 'Z' reduce it by subtracting 26(no.of alphabets) to keep in boundaries of ascii values of 'A' and 'Z'
if(c>'Z')
c=c-26;
}
//encryption logic for lowercase letters
else if(Character.isLowerCase(c))
{
c=(c+g)%26;
//if c value exceeds the ascii value of 'z' reduce it by subtracting 26(no.of alphabets) to keep in boundaries of ascii values of 'a' and 'z'
if(c>'z')
c=c-26;
}
//concatinate the encrypted characters/strings
encrypted=encrypted+(char) c;
}
return encrypted;}}//end of public class`
答案 0 :(得分:0)
看起来你正在循环文本循环中的关键字。这不是必要的。
您可以找到Vigenere Cipher at rosettacode的实现。 根据您的需要修改以下Java代码(例如检查大写/小写并相应地处理它们):
static String encrypt(String text, final String key) {
String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c < 'A' || c > 'Z') continue;
res += (char)((c + key.charAt(j) - 2 * 'A') % 26 + 'A');
j = ++j % key.length();
}
return res;
}
static String decrypt(String text, final String key) {
String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c < 'A' || c > 'Z') continue;
res += (char)((c - key.charAt(j) + 26) % 26 + 'A');
j = ++j % key.length();
}
return res;
}