2017-01-01 109 views
0

我一直在嘗試使用AES編寫加密文件,然後使用JCA中提供的密碼流進行解密。但是,在閱讀文件時,我遇到了問題,因爲解密過程很亂。使用CipherInputStream和CipherOutputStream對文件進行加密和解密

public class CipherStreams { 
public static void main(String[] args) { 
    try { 
     KeyGenerator keygen = KeyGenerator.getInstance("AES"); 
     Key k = keygen.generateKey(); 

     Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
     aes.init(Cipher.ENCRYPT_MODE, k); 
     FileOutputStream fs = new FileOutputStream("Encrypyed.txt"); 
     CipherOutputStream out = new CipherOutputStream(fs, aes); 
     out.write("[Hello:Okay]\nOkay".getBytes()); 
     out.close(); 

     Cipher aes2 = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
     aes2.init(Cipher.DECRYPT_MODE, k); 

     FileInputStream fis = new FileInputStream("Encrypyed.txt"); 
     CipherInputStream in = new CipherInputStream(fis,aes2); 
     byte[] b = new byte[8]; 
     int i = in.read(b); 
     while(i!=-1) { 
      System.out.print((char)i); 
      i = in.read(b); 
     } 
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException ex) { 
     Logger.getLogger(CipherStreams.class.getName()).log(Level.SEVERE, null, ex); 
    } 
} 
} 

我收到一個單字節輸出爲5.任何人都可以請幫忙指出這個問題嗎?

回答

4

您沒有寫入讀取的字節,而是正在寫入正在讀取的字節數。

您還假設默認平臺編碼只是將每個字符轉換爲一個字節。

只是做寫作時你做了什麼,相反的:讀到的一切,和讀取的字節數組轉換爲字符串,然後打印該字符串:

public class CipherStreams { 
    public static void main(String[] args) { 
     try { 
      KeyGenerator keygen = KeyGenerator.getInstance("AES"); 
      Key k = keygen.generateKey(); 

      Cipher aes = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
      aes.init(Cipher.ENCRYPT_MODE, k); 
      String fileName = "Encrypted.txt"; 
      FileOutputStream fs = new FileOutputStream(fileName); 
      CipherOutputStream out = new CipherOutputStream(fs, aes); 
      out.write("[Hello:Okay]\nOkay".getBytes()); 
      out.flush(); 
      out.close(); 

      Cipher aes2 = Cipher.getInstance("AES/ECB/PKCS5Padding"); 
      aes2.init(Cipher.DECRYPT_MODE, k); 

      FileInputStream fis = new FileInputStream(fileName); 
      CipherInputStream in = new CipherInputStream(fis, aes2); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 

      byte[] b = new byte[1024]; 
      int numberOfBytedRead; 
      while ((numberOfBytedRead = in.read(b)) >= 0) { 
       baos.write(b, 0, numberOfBytedRead); 
      } 
      System.out.println(new String(baos.toByteArray())); 
     } 
     catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IOException ex) { 
      ex.printStackTrace(); 
      ; 
     } 
    } 
} 
+0

這工作。我沒有意識到我正在寫入讀取的字節數。謝謝! –

相關問題