2013-04-09 44 views
1

我正在測試Java中的文本加密。問題是,我在行首開始出現一些奇怪的字符,我不明白爲什麼。當我刪除加密一切順利。Java CipherInputStream將奇怪的字符放在行首

當複製到記事本+ +,輸出的樣子:

Hello 

<SOH>dear 

<STX><STX>world 

爲什麼會出現奇怪的控制字符?

代碼:

public class Test { 
     private static File file; 
     private static final byte[] STAT_KEY = { -1, -2, 3, 4, -5, -6, -7, 8 }; 
     static { 
      file = new File("MyFile.txt"); 
     } 

     private static Cipher getCipher(int mode) throws InvalidKeyException, NoSuchAlgorithmException, 
       InvalidKeySpecException, NoSuchPaddingException { 
      DESKeySpec dks = new DESKeySpec(STAT_KEY); 
      SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); 
      SecretKey desKey = skf.generateSecret(dks); 
      Cipher cipher = Cipher.getInstance("DES"); 
      cipher.init(mode, desKey); 
      return cipher; 
     } 

     private static void appendToFile(String item) throws Exception { 
      CipherOutputStream cos = null; 
      try { 
       cos = new CipherOutputStream(new FileOutputStream(file, true), getCipher(Cipher.ENCRYPT_MODE)); 
       cos.write((item + String.format("%n")).getBytes()); 
      } finally { 
       cos.close(); 
      } 
     } 

     private static void readFromFile() throws Exception { 
      CipherInputStream cis = null; 
      try { 
       cis = new CipherInputStream(new FileInputStream(file), getCipher(Cipher.DECRYPT_MODE)); 
       int content; 
       while ((content = cis.read()) != -1) { 
        System.out.print((char) content); 
       } 
      } finally { 
       cis.close(); 
      } 
     } 

     public static void main(String[] args) throws Exception { 
      String[] items = { "Hello", "dear", "world" }; 
      for (String item : items) { 
       appendToFile(item); 
      } 
      readFromFile(); 
     } 
    } 

PD:對不起,我處理異常:)

+0

對於簡單的複製/粘貼示例爲+1。 – 2013-04-09 13:25:54

+0

我編輯了你的問題,因爲當你看到記事本++解釋的控制字符時,它更容易理解。 – 2013-04-09 14:34:44

+0

好的,謝謝你,對你們倆 – dalvarezmartinez1 2013-04-09 15:26:41

回答

1

很像ObjectOutputStream的方式,CipherOutputStream不寫入的方式,允許直接追加。

追加(數據1)+追加(數據2)+追加(數據3)!=追加(DATA1 + DATA2 + DATA3)

您需要添加自己劃定不同的數據塊的方法。有趣的?字符是CipherOutputStream使用的專用控制字符。

如果您只是正常加密數據(即使用Cipher對象)並將輸出寫入到由適當的分隔符包圍的文件中,生活可能會更容易。

+0

通過追加你的意思cos.write((item + String.format(「%n」))。getBytes() );線?我的目標是按行寫文本,所以我試圖在每個字符串的末尾附加一個新的行char。 我的英文我不夠好,你會不會提供一些代碼,最後一句的僞代碼。我如何正常加密數據?我知道在加密之後,我應該使用正常的FileOutputStream將此加密數據寫入文件。 – dalvarezmartinez1 2013-04-09 15:35:27

+0

好的,所以我想我解決了它,正如你所說,我發現了一種方法來加密一個字符串在這裏:http://stackoverflow.com/questions/1205135/how-to-encrypt-string-in-java 而我'使用普通的FileOutputStream來輸出結果到文件。現在我在某些單詞前面找到了\ 00 \ 00 \ 00,但可能與填充有關 – dalvarezmartinez1 2013-04-09 16:41:14

+0

你用什麼作爲分隔符?只是一個換行符? – 2013-04-10 06:52:46