2017-10-05 71 views
1

我正在嘗試編寫一個加密文件,該文件將使用gpg進行解密,並將逐行寫入而不是寫入一個塊。我在GnuPG中生成了密鑰,並使用公鑰進行加密。下面是我使用的加密方法:使用BouncyCastle PGP實用程序增量加密Java中的

public static byte[] encrypt(byte[] clearData, PGPPublicKey encKey, 
      String fileName,boolean withIntegrityCheck, boolean armor) 
      throws IOException, PGPException, NoSuchProviderException { 
     if (fileName == null) { 
      fileName = PGPLiteralData.CONSOLE; 
     } 

     ByteArrayOutputStream encOut = new ByteArrayOutputStream(); 

     OutputStream out = encOut; 
     if (armor) { 
      out = new ArmoredOutputStream(out); 
     } 

     ByteArrayOutputStream bOut = new ByteArrayOutputStream(); 

     PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
       PGPCompressedDataGenerator.ZIP); 
     OutputStream cos = comData.open(bOut); // open it with the final 
     // destination 
     PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator(); 

     // we want to generate compressed data. This might be a user option 
     // later, 
     // in which case we would pass in bOut. 
     OutputStream pOut = lData.open(cos, // the compressed output stream 
       PGPLiteralData.BINARY, fileName, // "filename" to store 
       clearData.length, // length of clear data 
       new Date() // current time 
       ); 
     pOut.write(clearData); 

     lData.close(); 
     comData.close(); 

     PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_192).setSecureRandom(new SecureRandom())); 


     cPk.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey)); 

     byte[] bytes = bOut.toByteArray(); 

     OutputStream cOut = cPk.open(out, bytes.length); 

     cOut.write(bytes); // obtain the actual bytes from the compressed stream 

     cOut.close(); 

     out.close(); 

     return encOut.toByteArray(); 
    } 

而且我有一個小的原型測試類使用像這樣的方法:

  PGPPublicKey pubKey = PGPEncryptionTools.readPublicKeyFromCol(new FileInputStream(appProp.getKeyFileName())); 

     byte[] encryptbytes = PGPEncryptionTools.encrypt("\nthis is some test text".getBytes(), pubKey, null, true, false); 
     byte[] encryptbytes2 = PGPEncryptionTools.encrypt("\nmore test text".getBytes(), pubKey, null, true, false); 

     FileOutputStream fos = new FileOutputStream("C:/Users/me/workspace/workspace/spring-batch-project/resources/encryptedfile.gpg"); 
     fos.write(encryptbytes); 
     fos.write(encryptbytes2); 
     fos.flush(); 
     fos.close(); 

所以這造成encryptedfile.gpg,但是當我去的GnuPG解密文件,它的工作原理,但它只輸出第一行「這是一些測試文本」。

如何修改此代碼以便能夠加密兩條線並讓GnuPG解密它們?

回答

1

您每次調用PGPEncryptionTools.encrypt(...)方法都會生成多個獨立的OpenPGP消息。要僅輸出單個OpenPGP消息(GnuPG也可以在單次運行中解密),請將所有純文本寫入單個流(在代碼中稱爲pOut),並且在最後將最後一個字節寫入流之前不要關閉此消息。

+0

例如,如果能夠打開這個流並在spring批處理中以塊的形式繼續寫入數據流,然後關閉流以創建一個加密文件,那麼這樣做是可能的嗎? – Novacane

+0

是的,確切地說。只要您寫入單個流,就會創建一條OpenPGP消息。 –