2016-11-10 143 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; 
    }