You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Bouncy Castle实现Java PGP加密后无法自行解密问题求助

问题根因

加密方法中流的写入目标配置错误:
你调用PGPLiteralDataGenerator.open()生成字面数据输出流时,错误地将装甲输出流aOut作为入参,明文数据没有经过加密流程就直接写入了装甲输出,最终生成的PGP报文结构不符合规范,所以解密失败。

修复方案

修改encrypt方法中PGPLiteralDataGenerator.open()的入参,将aOut替换为加密生成器返回的cOut即可,修正后的核心代码如下:

public static byte[] encrypt(byte[] bytes, String publicKey) throws IOException {

    ByteArrayOutputStream encOut = new ByteArrayOutputStream();

    try {
        PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(PGPEncryptedData.AES_128)
                        .setSecureRandom(new SecureRandom())
                        .setWithIntegrityPacket(true)
                        .setProvider("BC"));

        PGPPublicKey encryptionKey = readPublicKey(publicKey);
        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encryptionKey).setProvider("BC"));

        ArmoredOutputStream aOut = new ArmoredOutputStream(encOut);
        OutputStream cOut = encGen.open(aOut, bytes.length);
        // write out the literal data
        PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
        // 这里把aOut替换为cOut,让明文先经过加密流程再写入装甲流
        OutputStream pOut = lData.open(cOut, PGPLiteralData.UTF8, PGPLiteralData.CONSOLE, bytes.length, new Date());
        pOut.write(bytes);
        pOut.close();

        // finish the encryption
        cOut.close();
        aOut.close();

    } catch (PGPException e) {
        log.error("Exception encountered while encoding data.", e);
    }
    return encOut.toByteArray();
}

如果需要和大多数PGP工具兼容,还可以在加密前增加数据压缩步骤,在明文写入加密流前先经过PGPCompressedDataGenerator处理即可。

内容的提问来源于stack exchange,提问作者Ambrozie Beniamin Paval

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:39:03