2017-07-17 17 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

相关问题