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

Java字符串PGP加密:BouncyCastle OpenPGP方法已弃用问题

解决使用BouncyCastle对JSON字符串进行PGP加密(避开废弃API)

我完全懂你的烦恼——网上搜出来的PGP加密示例大多还在沿用BouncyCastle早已废弃的OpenPGP方法,跑起来要么报错,要么留下兼容性隐患。下面给你一套基于BouncyCastle最新稳定版的实现方案,专门用来加密JSON文件里的字符串,全程用的都是当前推荐的API。

第一步:添加依赖

先确保你的项目引入了最新的BouncyCastle依赖(以Maven为例):

<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpg-jdk18on</artifactId>
    <version>1.77</version> <!-- 可替换为官网最新稳定版 -->
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcpkix-jdk18on</artifactId>
    <version>1.77</version>
</dependency>

第二步:完整实现代码

这套代码包含了JSON读取、公钥加载、PGP加密全流程,完全避开废弃方法:

import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.*;
import org.bouncycastle.openpgp.jcajce.JcaPGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDataEncryptorBuilder;
import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Iterator;

public class JsonPgpEncryptor {

    static {
        // 注册BouncyCastle安全提供者(如果项目未自动注册)
        Security.addProvider(new BouncyCastleProvider());
    }

    // 从文件读取有效PGP加密公钥
    private static PGPPublicKey readPublicKey(File publicKeyFile) throws IOException, PGPException {
        try (InputStream keyIn = new BufferedInputStream(new FileInputStream(publicKeyFile))) {
            JcaPGPPublicKeyRingCollection pgpPub = new JcaPGPPublicKeyRingCollection(keyIn);
            Iterator<PGPPublicKeyRing> keyRingIter = pgpPub.getKeyRings();
            
            while (keyRingIter.hasNext()) {
                PGPPublicKeyRing keyRing = keyRingIter.next();
                Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
                
                while (keyIter.hasNext()) {
                    PGPPublicKey key = keyIter.next();
                    // 只选择用于加密的密钥(排除签名密钥)
                    if (key.isEncryptionKey()) {
                        return key;
                    }
                }
            }
            throw new IllegalArgumentException("未在公钥文件中找到可用的加密密钥");
        }
    }

    // 加密JSON字符串核心方法
    public static void encryptJsonString(String jsonContent, PGPPublicKey publicKey, File outputFile) throws IOException, PGPException {
        byte[] jsonBytes = jsonContent.getBytes(StandardCharsets.UTF_8);

        // 输出ASCII装甲格式的加密内容(方便存储/传输)
        try (OutputStream out = new BufferedOutputStream(new FileOutputStream(outputFile));
             ArmoredOutputStream armoredOut = new ArmoredOutputStream(out)) {

            // 使用AES-256加密,开启完整性校验防止篡改
            PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
                    new JcaPGPDataEncryptorBuilder(PGPEncryptedData.AES_256)
                            .setWithIntegrityPacket(true)
                            .setSecureRandom(new java.security.SecureRandom())
                            .setProvider("BC"));

            // 添加公钥加密方式(只有对应私钥能解密)
            encryptor.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider("BC"));

            // 写入加密数据
            try (OutputStream encryptedOut = encryptor.open(armoredOut, jsonBytes.length)) {
                encryptedOut.write(jsonBytes);
                encryptedOut.flush();
            }
        }
    }

    // 读取JSON文件内容
    private static String readJsonFile(File jsonFile) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        // 替换为你的实际文件路径
        File jsonFile = new File("data.json");
        File publicKeyFile = new File("recipient-public-key.asc");
        File encryptedOutput = new File("encrypted-json.asc");

        try {
            String jsonContent = readJsonFile(jsonFile);
            PGPPublicKey publicKey = readPublicKey(publicKeyFile);
            encryptJsonString(jsonContent, publicKey, encryptedOutput);
            System.out.println("JSON加密完成!输出文件:" + encryptedOutput.getAbsolutePath());
        } catch (IOException | PGPException e) {
            e.printStackTrace();
        }
    }
}

关键说明

  • 废弃API规避:使用JcaPGPPublicKeyRingCollection、JcaPGPDataEncryptorBuilder等JCA兼容的新类,替代了旧版中已标记为废弃的构造方法和工具类。
  • 安全性保障:采用AES-256强加密算法,同时开启完整性校验包,有效防止加密内容被篡改。
  • 编码兼容性:全程使用UTF-8编码处理JSON字符串,避免出现乱码问题。
  • ASCII装甲格式:生成的加密内容是可读的ASCII格式,比二进制格式更适合存储和网络传输。

注意事项

  1. 确保你的PGP公钥是加密密钥(不是签名密钥),代码中通过key.isEncryptionKey()做了校验。
  2. 如果需要加密超大JSON文件,可以修改代码为流式处理,避免一次性加载全部内容到内存。
  3. 若项目未自动注册BouncyCastle提供者,代码中的静态代码块会帮你完成注册。

内容的提问来源于stack exchange,提问作者Preetam Roy Choudhury

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:05:44