2016-11-10 207 views
0

我有一个文本文件,我已经使用移位加密,但我需要再次加密加密文本,但这次使用vigenere密码。然后,我需要解密该加密文本(vigenere首先然后移动),但所有的大写和小写字母需要保持不变,以及黑色空格,引号,逗号和句号。我已经完成了移位加密和解密所有剩下的就是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

它看起来像你在文本循环内循环关键字。这没有必要。

您可以找到Vigenere密码的实现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; 
    }