在Java中刷新PGP加密的Bouncy Castle OutputStream

时间:2015-02-24 20:03:31

标签: java encryption bouncycastle pgp

我正在研究概念验证Java应用程序,该应用程序从PGP加密文件中读取一系列换行符分隔的请求,处理这些请求,然后将响应写入另一个PGP加密文件,并在之后刷新每个回复写。

我已成功将Bouncy Castle 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;
}

当我显式调用flush()时,返回的OutputStream不会刷新。只有在每个compressedOut,encryptedOut和armoredOut OutputStream上调用close()方法时,它们才会被刷新。

我试图修改Bouncy Castle源代码,但我所做的一切都会导致某些格式错误或损坏的PGP消息无法解密。我还尝试修改缓冲区大小,使其更小,更大,并确保单个请求的确切大小,但这不起作用。

有没有人对如何使用Bouncy Castle手动刷新加密的OutputStream有任何建议?

1 个答案:

答案 0 :(得分:1)

我和BC有同样的问题。查看ArmoredOutputStream课程。 Flush为空,close并未将其称为基础输出流关闭。这意味着,如果您正在使用ArmoredOutputStreamArmoredInputStream,则必须关闭ArmoredOutputStream本身和基础Outputstream。同样的冲洗!