2017-02-17 116 views
0

我試圖使AES加密,我正在生成鹽。但是我遇到了一些問題。下面的代碼工作正常,但每當我加密第二個等文件,文件中的鹽被覆蓋。有關如何將salt byte []添加到salt fil中而不覆蓋它的任何建議?如何將字節數組附加到文件而不覆蓋它使用java

夥計們..我更新了我的代碼..感謝那部分,雖然它修復了覆蓋問題,但它並沒有使它到下一行。

輸出我的文件:?〜V「A·Ò²Ö4ô|ŒT‰mÊî0'Z^'U•蘇克·=這是二鹽結合

任何想法如何使它在追加下一行

我想saltoutfile.write( 「/ N」),但不工作

public byte[] generateSalt() throws IOException{ 
      //generate Salt value 
      // password, iv and salt should be transferred to the other end 
      // in a secure manner 
      // salt is used for encoding 
      // writing it to a file 
      // salt should be transferred to the recipient securely 
      // for decryption 
    byte[] salt = new byte[8]; 
    SecureRandom secureRandom = new SecureRandom(); 
    secureRandom.nextBytes(salt); 
      FileOutputStream saltOutFile = new FileOutputStream("C:\\KryptZIP\\salt.enc" , true); 
      saltOutFile.write(salt); 
     saltOutFile.close(); 
      return salt; 


} 
在評論中提及

:這是我讀鹽值

public static byte[] readSalt() throws IOException{ 
    // reading the salt 
      // user should have secure mechanism to transfer the 
      // salt, iv and password to the recipient 
      FileInputStream saltFis = new FileInputStream("C:\\KryptZIP\\salt.enc"); 
      byte[] salt = new byte[8]; 
      saltFis.read(salt); 
      saltFis.close(); 
      return salt; 
} 
+0

出了什麼問題['新的FileOutputStream中(文件名,真實)'](https://docs.oracle.com/javase/8/docs/api/java/ IO/FileOutputStream.html#FileOutputStream中,java.lang.String中-boolean-)? – Seelenvirtuose

+0

我沒有看到任何問題。每次運行代碼時,它會將8個字節的數據附加到salt文件中。 – anacron

+0

假設我使用這個: FileOutputStream saltOutFile = new FileOutputStream(「C:\\ KryptZIP \\ salt.enc」,true); 這會將下一個鹽添加到鹽文件?因爲我不知道它是否會顯示爲下一行 –

回答

0

使用Apache FileUtils。使用方法

FileUtils.writeByteArrayToFile(java.io.File file,bytes[] content,boolean append) 
+0

爲什麼使用整個庫,如果一個簡單的['new FileOutputStream(filename,true)'](https://docs.oracle.com/javase/8/docs/api/java/io/FileOutputStream.html#FileOutputStream- java.lang.String-boolean-)會做什麼? – Seelenvirtuose

+0

作爲庫句柄來關閉資源 –

4

您需要使用帶有2個參數的FileOutputStream的構造函數。第二個參數是一個布爾標誌,指示您是否想從(false)開始附加true)到文件或寫入

你的代碼更改爲:

FileOutputStream saltOutFile = new FileOutputStream("C:\\KryptZIP\\salt.enc", true); 
+0

不錯的解決方案bro。但任何想法如何使下一行鹽,而不是在行的末尾? –

+0

你總是可以在鹽的末尾寫一個換行符('saltOutFile.write('\ n');')。但既然這是二進制數據,你爲什麼要這麼做?在任何情況下,您都無法使用文本編輯器閱讀它。 –

+0

原因是我使用它進行加密,目前我無法讀取正確加密的正確鹽。 例子我加密A.產生鹽A.存儲到鹽文件 當我加密B.生成鹽B ..存儲B文件。 我無法確定哪個鹽是哪個..因此plannig使它成爲不同的線 –

相關問題