2015-02-24 34 views
1

我正在研究概念證明Java應用程序,它從PGP加密文件讀取一系列換行分隔的請求,處理這些請求,然後將響應寫入另一個PGP加密後的文件,每次寫入響應後都會刷新。刷新PGP加密的Bouncy Castle OutputStream in Java

我已經成功地集成充氣城堡1.5與我與我似乎無法刷新的命令輸出中的例外適用:

private ArmoredOutputStream armoredOut = null; 
private OutputStream compressedOut = null; 
private OutputStream encryptedOut = null; 

public OutputStream encryptStream(OutputStream outputStream){ 
    OutputStream literalOut = null; 
    try{ 
     armoredOut = new ArmoredOutputStream(outputStream); 
     BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_256); 
     dataEncryptor.setSecureRandom(new SecureRandom()); 
     PGPEncryptedDataGenerator encryptGen = new PGPEncryptedDataGenerator(dataEncryptor); 

     PGPPublicKey publicKey = null; 
     InputStream publicKeyStream = null; 
     try{ 
      publicKeyStream = this.getClass().getClassLoader().getResourceAsStream(keyName); 
      publicKey = getEncryptionKey(publicKeyStream); 
     } 
     finally{ 
      if(publicKeyStream != null){ 
       publicKeyStream.close(); 
      } 
     } 
     if(publicKey == null){ 
      throw new IllegalArgumentException("Couldn't obtain public key."); 
     } 

     encryptGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey)); 

     encryptedOut = encryptGen.open(armoredOut, new byte[bufferSize]); 

     PGPCompressedDataGenerator compressGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); 
     compressedOut = compressGen.open(encryptedOut); 

     PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator(); 
     literalOut = literalGen.open(compressedOut, PGPLiteralDataGenerator.UTF8, "Response", new Date(), new byte[bufferSize]); 
    } 
    catch(PGPException e){ 
     LOGGER.error(ExceptionUtils.getStackTrace(e)); 
    } 
    catch(IOException e){ 
     LOGGER.error(ExceptionUtils.getStackTrace(e)); 
    } 
    return literalOut; 
} 

返回的OutputStream不刷新的時候我明確調用flush()。只有在每個compressedOut,encryptedOut和armoredOut OutputStreams上調用close()方法時,它們纔會被實際刷新。

我試圖修改Bouncy Castle源代碼,但是我所做的一切都會導致某些格式不正確或損壞的PGP消息無法解密。我也嘗試修改緩衝區大小,使其更小,更大,並確保單個請求的大小,但這不起作用。

有沒有人有任何建議如何手動沖洗加密的OutputStream與Bouncy城​​堡?

+0

我不熟悉BC PGP庫,但對於許多編碼/加密構造,flush沒有意義,因此不被支持。例如,加密通常以最終塊的填充方案爲塊定向。並且base64編碼類似於面向最終塊的填充方案的面向塊。沒有辦法「刷新」和不完整的塊,繼續編碼。 – 2015-02-26 03:24:24

回答

0

我和BC有同樣的問題。看看ArmoredOutputStream課程。 Flush爲空,並且close不會將其調用的底層輸出流關閉。這意味着如果您使用的是ArmoredOutputStreamArmoredInputStream,則必須關閉ArmoredOutputStream本身以及底層的Outputstream。同花順!

相關問題