2017-07-17 65 views
-1

我有一個程序正在加密一個文本文件,並保存編碼的txt和密鑰seperatly。現在我試着編寫使用密鑰解密文件的解密程序。我讀了鑰匙,但似乎我不能像這樣使用它。有沒有人對我有任何建議,或者甚至不可能這樣做?java - 用外部密鑰解密文本文件

public class decrypt { 

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException { 

     try { 
      File fileDir = new File("C:/xxx/key.txt"); 

      BufferedReader in = new BufferedReader(
         new InputStreamReader(new FileInputStream(fileDir), "UTF-8")); 
      String str; 

      while ((str = in.readLine()) != null) { 
       System.out.println(str); 
      } 

      in.close(); 
      }catch (UnsupportedEncodingException e){ 
       System.out.println(e.getMessage()); 
      }catch (IOException e){ 
       System.out.println(e.getMessage()); 
      }catch (Exception e){ 
       System.out.println(e.getMessage()); 
      } 


     byte[] decodedKey = Base64.getDecoder().decode(str); 
     SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); 

    } 
} 

回答

-1

str = in.readLine()不附加文字str,而是創建一個包含下一行,而不是一個新的字符串。 你應該做到以下幾點:

StringBuilder sb = new StringBuilder(); 

然後在while循環:

sb.append(str); 

而在最後,你可以得到你的字符串的內容通過調用

sb.toString() 

編輯:或者如果這種方式更清晰,更完整的例子:

String line; 
StringBuilder sb = new StringBuilder(); 

while ((line = in.readLine()) != null) { 
    sb.append(line); 
    sb.append("\n"); 
    System.out.println(line); 
} 

String content = sb.toString(); 
+0

謝謝你的工作! –

+0

很高興我能幫到你。你現在可以接受我的答案,哈哈。 – mumpitz

+0

我會,網站期待我再等3分鐘,直到我可以,哈哈 –

0

解密文本文件

你的問題已經沒有意義。加密的結果不是文本文件。所以你沒有企圖試圖讀取Reader擺在首位。

你需要看看CipherInputStream