【发布时间】:2015-04-26 15:09:44
【问题描述】:
我正在开发一个概念验证 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 输出流上调用close() 方法时,它们才会真正被刷新。
我尝试修改 Bouncy Castle 源代码,但我所做的一切都会导致某种格式错误或损坏的 PGP 消息无法解密。我还尝试修改缓冲区大小,使其更小、更大,以及单个请求的确切大小,但这不起作用。
有人对如何使用 Bouncy Castle 手动刷新加密的 OutputStream 有任何建议吗?
【问题讨论】:
-
我不熟悉 BC PGP 库,但对于许多编码/加密结构,flush 没有意义,因此不受支持。例如,加密通常是面向块的,最后一个块有一个填充方案。并且 base64 编码同样是面向块的,最后一个块有一个填充方案。没有办法“刷新”和不完整的块并继续编码。
标签: java encryption bouncycastle pgp