如何在Spring Boot中使用PGP加密TXT文件?
在Spring Boot中实现PGP加密TXT文件
1. 添加BouncyCastle依赖
PGP加密依赖BouncyCastle密码库,在pom.xml中添加以下依赖:
<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>
2. 编写PGP加密工具类
创建工具类封装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.JcaKeyFingerprintCalculator; import org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder; import org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator; import java.io.*; import java.security.Security; public class PgpEncryptionUtil { static { Security.addProvider(new BouncyCastleProvider()); } /** * PGP加密文件 * @param inputFilePath 待加密文件路径 * @param outputFilePath 加密后文件路径 * @param publicKeyFilePath PGP公钥文件路径 * @throws IOException, PGPException */ public static void encryptFile(String inputFilePath, String outputFilePath, String publicKeyFilePath) throws IOException, PGPException { PGPPublicKey publicKey = readPublicKey(publicKeyFilePath); try (OutputStream out = new ArmoredOutputStream(new FileOutputStream(outputFilePath)); InputStream in = new BufferedInputStream(new FileInputStream(inputFilePath))) { PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5) .setWithIntegrityPacket(true) .setSecureRandom(new java.security.SecureRandom()) .setProvider("BC")); encryptor.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey).setProvider("BC")); OutputStream encryptedOut = encryptor.open(out, new byte[4096]); PGPLiteralDataGenerator literalGenerator = new PGPLiteralDataGenerator(); OutputStream literalOut = literalGenerator.open(encryptedOut, PGPLiteralData.BINARY, new File(inputFilePath), System.currentTimeMillis(), new byte[4096]); byte[] buf = new byte[4096]; int len; while ((len = in.read(buf)) != -1) { literalOut.write(buf, 0, len); } literalOut.close(); encryptedOut.close(); } } /** * 读取PGP公钥 */ private static PGPPublicKey readPublicKey(String publicKeyFilePath) throws IOException, PGPException { try (InputStream keyIn = new BufferedInputStream(new FileInputStream(publicKeyFilePath))) { PGPPublicKeyRingCollection keyRingCollection = new JcaPGPPublicKeyRingCollection(keyIn, new JcaKeyFingerprintCalculator()); for (PGPPublicKeyRing keyRing : keyRingCollection) { for (PGPPublicKey key : keyRing) { if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("公钥文件中未找到可用的加密密钥"); } } }
3. 整合加密逻辑到原有代码
修改你生成TXT文件的方法,在文件写入完成后调用PGP加密方法:
import java.io.*; import java.util.ArrayList; import java.util.List; public class TxtService { public List<String> generateAndEncryptTxt(List<String> data) throws IOException { // 生成明文TXT文件 File txtFile = new File("C:\\Downloads\\test.txt"); try (PrintWriter writer = new PrintWriter(new FileWriter(txtFile))) { for (String line : data) { writer.println(line); } } // 执行PGP加密 try { String encryptedFilePath = "C:\\Downloads\\test.txt.pgp"; String publicKeyPath = "C:\\Keys\\public_key.asc"; // 替换为你的公钥文件实际路径 PgpEncryptionUtil.encryptFile(txtFile.getAbsolutePath(), encryptedFilePath, publicKeyPath); // 可选:删除明文文件 txtFile.delete(); } catch (Exception e) { throw new RuntimeException("PGP加密失败", e); } return data; } // 测试示例 public static void main(String[] args) throws IOException { List<String> info = new ArrayList<>(); info.add("hello world"); new TxtService().generateAndEncryptTxt(info); } }
关键注意事项
- 需提前生成有效的PGP密钥对,公钥用于加密,私钥用于解密
- 公钥文件通常为
.asc格式的ASCII armored文件 - 路径处理可使用
File.separator适配跨平台环境
内容的提问来源于stack exchange,提问作者Fabian Andres Ortiz Valiente
相关产品推荐
相关产品推荐

