簡體   English   中英

將CipherInputStream寫入文本文件

[英]Writing CipherInputStream to a text file

我正在嘗試解密存儲在文本文件中的加密數據。 我使用相同的密鑰和IV進行加密和解密,然后通過配置文件進行傳輸。

當我將CipherInputStream打印到控制台時,確實得到了一些內容,但是當我嘗試將其寫入文本文件時,卻沒有得到任何內容。

這是我的問題的一段代碼:

File encryptedData = new File("C:\\Users\\Victoria\\Desktop\\encryptedData.txt");
File decryptedData = new File("C:\\Users\\Victoria\\Desktop\\decryptedData.txt");
FileInputStream inputStream = new FileInputStream(encryptedData);
byte[] inputBytes = new byte[(int) decryptedData.length()];
inputStream.read(inputBytes);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, newkey, newiv, SecureRandom.getInstance("SHA1PRNG"));
CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
FileOutputStream outputStream = new FileOutputStream(decryptedData);
System.out.println("cipherInputStream: " + cipherInputStream);  

// Writing the decrypted content to an output file
byte[] buff = new byte[1024 * 10];
int length;
while ((length = cipherInputStream.read(buff)) > 0) {
    outputStream.write(buff, 0, length);
}
bufin.close();
outputStream.close();
cipherInputStream.close();

有什么辦法嗎? 謝謝!

存儲在文本文件中的加密數據

就此而言,這已經是一個矛盾。 加密的數據是二進制文件,而不是文本文件,不應存儲在擴展名為.txt文件中。

byte[] inputBytes = new byte[(int) decryptedData.length()];

這行代碼毫無意義。 您尚不知道解密的數據將持續多長時間。 解密的文件甚至可能不存在,在這種情況下,這將產生一個零長度的數組。 或者它可能與要生產的產品不同,在這種情況下,長度是錯誤的。

inputStream.read(inputBytes);

刪除此行及其前面的那一行。

  1. 它會讀入一個數組,該數組的大小最好等於解密數據的大小,對於加密數據來說這是錯誤的大小,而在最壞的情況下,它的大小就是錯誤的,甚至是零長度,如上所述。
  2. 它可能會讀取輸入,直到大小不正確的緩沖區填滿為止,然后您(a)完全忽略讀取的數據,並且(b)嘗試進一步讀取同一流,這將導致解密循環失敗,或者充其量只能產生錯誤的輸出,因為您可能沒有解密所有數據。

當我將CipherInputStream打印到控制台時,我確實得到了一些內容

不,你不會。 你得到了一塊一般形式的數據CipherInputStream@0011223344 ,這是調用的只是結果CipherInputStream.toString()包含任何“內容”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM