使用 java 对文件进行pgp加密的完整工具类代码

时间: 2024-01-22 22:18:07 浏览: 29
下面是一个使用 BouncyCastle 实现 PGP 加密和解密的 Java 工具类示例: ```java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.NoSuchProviderException; import java.security.SecureRandom; import java.security.Security; import java.util.Date; import java.util.Iterator; import org.bouncycastle.bcpg.ArmoredOutputStream; import org.bouncycastle.bcpg.CompressionAlgorithmTags; import org.bouncycastle.bcpg.HashAlgorithmTags; import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; import org.bouncycastle.bcpg.sig.Features; import org.bouncycastle.bcpg.sig.KeyFlags; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openpgp.PGPEncryptedData; import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPLiteralData; import org.bouncycastle.openpgp.PGPObjectFactory; import org.bouncycastle.openpgp.PGPOnePassSignatureList; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPPublicKey; import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData; import org.bouncycastle.openpgp.PGPPublicKeyRing; import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; import org.bouncycastle.openpgp.PGPSecretKey; import org.bouncycastle.openpgp.PGPSecretKeyRing; import org.bouncycastle.openpgp.PGPSecretKeyRingCollection; import org.bouncycastle.openpgp.PGPUtil; public class PgpEncryptDecryptUtil { private static final String PROVIDER = "BC"; private static final int BUFFER_SIZE = 4096; // 加载 BouncyCastle 提供的 JCE 供应商 static { Security.addProvider(new BouncyCastleProvider()); } /** * 加密数据并输出到指定的输出流中 * * @param data 要加密的数据 * @param publicKeyIn 加载公钥的输入流 * @param outputStream 输出加密后的数据的输出流 * @throws IOException IO异常 * @throws PGPException PGP异常 */ public static void encrypt(byte[] data, InputStream publicKeyIn, OutputStream outputStream) throws IOException, PGPException { // 创建公钥环 PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(publicKeyIn)); // 找到可用的公钥 PGPPublicKey publicKey = null; Iterator<PGPPublicKeyRing> keyRingIterator = publicKeyRingCollection.getKeyRings(); while (publicKey == null && keyRingIterator.hasNext()) { PGPPublicKeyRing keyRing = keyRingIterator.next(); Iterator<PGPPublicKey> keyIterator = keyRing.getPublicKeys(); while (publicKey == null && keyIterator.hasNext()) { PGPPublicKey key = keyIterator.next(); if (key.isEncryptionKey()) { publicKey = key; } } } if (publicKey == null) { throw new IllegalArgumentException("Can't find public key"); } // 创建加密数据生成器 PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator( new JcePGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256) .setWithIntegrityPacket(true).setSecureRandom(new SecureRandom()).setProvider(PROVIDER)); encryptedDataGenerator.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(publicKey) .setProvider(PROVIDER)); // 创建压缩输出流 ByteArrayOutputStream compressedOutputStream = new ByteArrayOutputStream(); OutputStream compressedDataOutputStream = new ArmoredOutputStream(compressedOutputStream); PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator( CompressionAlgorithmTags.ZIP); OutputStream compressedDataOutputStream2 = compressedDataGenerator.open(compressedDataOutputStream); // 创建字面数据输出流 PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator(); OutputStream literalDataOutputStream = literalDataGenerator.open(compressedDataOutputStream2, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, data.length, new Date()); // 写入明文数据 ByteArrayInputStream dataInputStream = new ByteArrayInputStream(data); byte[] buffer = new byte[BUFFER_SIZE]; int length; while ((length = dataInputStream.read(buffer, 0, buffer.length)) != -1) { literalDataOutputStream.write(buffer, 0, length); } literalDataOutputStream.close(); // 关闭输出流 compressedDataGenerator.close(); compressedDataOutputStream.close(); compressedOutputStream.close(); // 加密数据并输出到指定输出流 byte[] encryptedData = compressedOutputStream.toByteArray(); OutputStream encryptedDataOutputStream = encryptedDataGenerator.open(outputStream, encryptedData.length); encryptedDataOutputStream.write(encryptedData); encryptedDataOutputStream.close(); } /** * 解密数据并返回解密后的数据 * * @param encryptedDataIn 加载加密数据的输入流 * @param privateKeyIn 加载私钥的输入流 * @return 解密后的数据 * @throws IOException IO异常 * @throws PGPException PGP异常 */ public static byte[] decrypt(InputStream encryptedDataIn, InputStream privateKeyIn) throws IOException, PGPException { // 创建私钥环 PGPSecretKeyRingCollection secretKeyRingCollection = new PGPSecretKeyRingCollection( PGPUtil.getDecoderStream(privateKeyIn)); // 找到可用的私钥 PGPPrivateKey privateKey = null; Iterator<PGPSecretKeyRing> keyRingIterator = secretKeyRingCollection.getKeyRings(); while (privateKey == null && keyRingIterator.hasNext()) { PGPSecretKeyRing keyRing = keyRingIterator.next(); Iterator<PGPSecretKey> keyIterator = keyRing.getSecretKeys(); while (privateKey == null && keyIterator.hasNext()) { PGPSecretKey key = keyIterator.next(); if (key.isSigningKey()) { privateKey = key.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder() .setProvider(PROVIDER).build("".toCharArray())); } } } if (privateKey == null) { throw new IllegalArgumentException("Can't find private key"); } // 创建对象工厂 PGPObjectFactory objectFactory = new PGPObjectFactory(PGPUtil.getDecoderStream(encryptedDataIn)); Object object = objectFactory.nextObject(); // 找到加密数据包 PGPEncryptedData encryptedData = null; while (encryptedData == null && object != null) { if (object instanceof PGPEncryptedData) { encryptedData = (PGPEncryptedData) object; } else { object = objectFactory.nextObject(); } } if (encryptedData == null) { throw new IllegalArgumentException("Can't find encrypted data"); } // 找到公钥并解密数据 InputStream encryptedDataInputStream = encryptedData.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder() .setProvider(PROVIDER).build(privateKey)); PGPObjectFactory encryptedObjectFactory = new PGPObjectFactory(encryptedDataInputStream); object = encryptedObjectFactory.nextObject(); // 找到签名列表并校验签名 PGPOnePassSignatureList signatureList = null; while (signatureList == null && object != null) { if (object instanceof PGPOnePassSignatureList) { signatureList = (PGPOnePassSignatureList) object; } else { object = encryptedObjectFactory.nextObject(); } } if (signatureList != null) { throw new PGPException("This implementation doesn't support signed data"); } // 找到字面数据包并解压缩数据 PGPLiteralData literalData = null; while (literalData == null && object != null) { if (object instanceof PGPLiteralData) { literalData = (PGPLiteralData) object; } else { object = encryptedObjectFactory.nextObject(); } } if (literalData == null) { throw new IllegalArgumentException("Can't find literal data"); } ByteArrayOutputStream uncompressedOutputStream = new ByteArrayOutputStream(); InputStream compressedDataInputStream = literalData.getInputStream(); PGPCompressedData compressedData = new PGPCompressedData(compressedDataInputStream); InputStream uncompressedDataInputStream = compressedData.getDataStream(); byte[] buffer = new byte[BUFFER_SIZE]; int length; while ((length = uncompressedDataInputStream.read(buffer, 0, buffer.length)) != -1) { uncompressedOutputStream.write(buffer, 0, length); } uncompressedDataInputStream.close(); compressedDataInputStream.close(); uncompressedOutputStream.close(); return uncompressedOutputStream.toByteArray(); } /** * 加载公钥环 * * @param publicKeyRingIn 加载公钥环的输入流 * @return 公钥环 * @throws IOException IO异常 * @throws PGPException PGP异常 */ public static PGPPublicKeyRingCollection loadPublicKeyRing(InputStream publicKeyRingIn) throws IOException, PGPException { return new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(publicKeyRingIn)); } /** * 加载私钥环 * * @param secretKeyRingIn 加载私钥环的输入流 * @return 私钥环 * @throws IOException IO异常 * @throws PGPException PGP异常 */ public static PGPSecretKeyRingCollection loadSecretKeyRing(InputStream secretKeyRingIn) throws IOException, PGPException { return new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(secretKeyRingIn)); } /** * 从文件中加载公钥环 * * @param publicKeyRingFile 加载公钥环的文件 * @return 公钥环 * @throws IOException IO异常 * @throws PGPException PGP异常 */ public static PGPPublicKeyRingCollection loadPublicKeyRingFromFile(String publicKeyRingFile) throws IOException, PGPException { FileInputStream fileInputStream = new FileInputStream(publicKeyRingFile); PGPPublicKeyRingCollection publicKeyRingCollection = loadPublicKeyRing(fileInputStream); fileInputStream.close(); return publicKeyRingCollection; } /** * 从文件中加载私钥环 * * @param secretKeyRingFile 加载私钥环的文件 * @return 私钥环 * @throws IOException IO异常 * @throws PGPException PGP异常 */ public static PGPSecretKeyRingCollection loadSecretKeyRingFromFile(String secretKeyRingFile) throws IOException, PGPException { FileInputStream fileInputStream = new FileInputStream(secretKeyRingFile); PGPSecretKeyRingCollection secretKeyRingCollection = loadSecretKeyRing(fileInputStream); fileInputStream.close(); return secretKeyRingCollection; } /** * 保存公钥环到文件中 * * @param publicKeyRing 要保存的公钥环 * @param publicKeyRingFileOut 保存公钥环的文件输出流 * @throws IOException IO异常 */ public static void savePublicKeyRing(PGPPublicKeyRing publicKeyRing, OutputStream publicKeyRingFileOut) throws IOException { ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(publicKeyRingFileOut); publicKeyRing.encode(armoredOutputStream); armoredOutputStream.close(); } /** * 保存私钥环到文件中 * * @param secretKeyRing 要保存的私钥环 * @param secretKeyRingFileOut 保存私钥环的文件输出流 * @throws IOException IO异常 */ public static void saveSecretKeyRing(PGPSecretKeyRing secretKeyRing, OutputStream secretKeyRingFileOut) throws IOException { ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(secretKeyRingFileOut); secretKeyRing.encode(armoredOutputStream); armoredOutputStream.close(); } /** * 保存公钥环到文件中 * * @param publicKeyRing 要保存的公钥环 * @param publicKeyRingFileOut 保存公钥环的文件输出流 * @throws IOException IO异常 */ public static void savePublicKeyRingToFile(PGPPublicKeyRing publicKeyRing, String publicKeyRingFileOut) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(publicKeyRingFileOut); savePublicKeyRing(publicKeyRing, fileOutputStream); fileOutputStream.close(); } /** * 保存私钥环到文件中 * * @param secretKeyRing 要保存的私钥环 * @param secretKeyRingFileOut 保存私钥环的文件输出流 * @throws IOException IO异常 */ public static void saveSecretKeyRingToFile(PGPSecretKeyRing secretKeyRing, String secretKeyRingFileOut) throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(secretKeyRingFileOut); saveSecretKeyRing(secretKeyRing, fileOutputStream); fileOutputStream.close(); } /** * 创建公钥环 * * @param keyPair 密钥对 * @param userId 用户ID * @param keyRingName 密钥环名称 * @param expirationTimeInDays 过期时间(以天为单位) * @return 公钥环 * @throws PGPException PGP异常 */ public static PGPPublicKeyRing createPublicKeyRing(PgpKeyPair keyPair, String userId, String keyRingName, int expirationTimeInDays) throws PGPException { PGPPublicKeyRingGenerator publicKeyRingGenerator = new PGPPublicKeyRingGenerator( PGPSignature.POSITIVE_CERTIFICATION, keyPair.getPublicKey(), userId, new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, new SecureRandom()) .setProvider(PROVIDER).build(keyPair.getPassphrase().toCharArray()), null, null, new JcaPGPContentSignerBuilder(keyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA256), new JcePGPKeyEncryptionMethodGenerator(keyPair.getPublicKey().getAlgorithm()) .setProvider(PROVIDER), new SecureRandom(), new Date()); if (expirationTimeInDays > 0) { publicKeyRingGenerator.addSubKey(keyPair.getPublicKey(), new Date(System.currentTimeMillis() + expirationTimeInDays * 86400000L), new JcaPGPContentSignerBuilder(keyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA256), new JcePGPKeyEncryptionMethodGenerator(keyPair.getPublicKey().getAlgorithm()).setProvider(PROVIDER)); } return publicKeyRingGenerator.generatePublicKeyRing(); } /** * 创建私钥环 * * @param keyPair 密钥对 * @param userId 用户ID * @param keyRingName 密钥环名称 * @param expirationTimeInDays 过期时间(以天为单位) * @return 私钥环 * @throws PGPException PGP异常 */ public static PGPSecretKeyRing createSecretKeyRing(PgpKeyPair keyPair, String userId, String keyRingName, int expirationTimeInDays) throws PGPException { PGPPublicKey publicKey = keyPair.getPublicKey(); PGPSecretKey secretKey = new PGPSecretKey(PGPSignature.DEFAULT_CERTIFICATION, publicKey, new JcaPGPContentSignerBuilder(publicKey.getAlgorithm(), HashAlgorithmTags.SHA256), new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, new SecureRandom()) .setProvider(PROVIDER).build(keyPair.getPassphrase().toCharArray()), null, null, new JcaPGPContentSignerBuilder(publicKey.getAlgorithm(), HashAlgorithmTags.SHA256), new JcePGPKeyEncryptionMethodGenerator(publicKey.getAlgorithm()).setProvider(PROVIDER)); if (expirationTimeInDays > 0) { secretKey = PGPSecretKey.addSecretSubKey(secretKey, keyPair.getPrivateKey(), new Date(System.currentTimeMillis() + expirationTimeInDays * 86400000L), new JcaPGPContentSignerBuilder(publicKey.getAlgorithm(), HashAlgorithmTags.SHA256), new JcePGPKeyEncryptionMethodGenerator(publicKey.getAlgorithm()).setProvider(PROVIDER)); } return new PGPSecretKeyRing(secretKey.getEncoded()); } /** * 创建密钥对 * * @param keySize 密钥长度 * @param passphrase 密码 * @return 密钥对 * @throws PGPException PGP异常 */ public static PgpKeyPair createKeyPair(int keySize, String passphrase) throws PGPException { JcaPGPKeyPairGenerator keyPairGenerator = new JcaPGPKeyPairGenerator().setProvider(PROVIDER); keyPairGenerator.generate(keySize, new SecureRandom()); PGPKeyPair keyPair = keyPairGenerator.generateKeyPair(); return new PgpKeyPair(keyPair.getPublicKey(), keyPair.getPrivateKey(), passphrase); } /** * 加载密钥对 * * @param publicKeyIn 加载公钥的输入流 * @param privateKeyIn 加载私钥的输入流 * @param passphrase 密码 * @return 密钥对 * @throws IOException IO异常 * @throws PGPException PGP异常 */ public static PgpKeyPair loadKeyPair(InputStream publicKeyIn, InputStream privateKeyIn, String passphrase) throws IOException,

相关推荐

最新推荐

recommend-type

C语言使用openSSL库DES模块实现加密功能详解

主要介绍了C语言使用openSSL库DES模块实现加密功能,简单讲解了DES加密的相关概念,并结合实例形式分析了DES加密的具体实现技巧,需要的朋友可以参考下
recommend-type

网络安全试验——pgp加密邮件

用pgp加密邮件 网络安全课实验报告。熟练掌握使用PGP软件,对邮件加解密的过程有所了解,是学生对加密过程,解密过程,不再陌生。了解加解密的原理等。
recommend-type

pgp邮件加密软件的安装使用实验报告

利用桌面pgp软件,进行通信邮件间的加密和解密,利用公钥私钥加密原理。实验报告有截图,有说明,有具体分析
recommend-type

软考-考生常见操作说明-202405101400-纯图版.pdf

软考官网--2024常见操作说明:包括如何绘制网络图、UML图、表格等 模拟作答系统是计算机技术与软件专业技术资格(水平)考试的电子化考试系统界面、作答过程的仿真系统,为各级别、各资格涉及输入和页面显示的部分题型提供体验性练习。
recommend-type

setuptools-34.0.3.zip

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解释minorization-maximization (MM) algorithm,并给出matlab代码编写的例子

Minorization-maximization (MM) algorithm是一种常用的优化算法,用于求解非凸问题或含有约束的优化问题。该算法的基本思想是通过构造一个凸下界函数来逼近原问题,然后通过求解凸下界函数的最优解来逼近原问题的最优解。具体步骤如下: 1. 初始化参数 $\theta_0$,设 $k=0$; 2. 构造一个凸下界函数 $Q(\theta|\theta_k)$,使其满足 $Q(\theta_k|\theta_k)=f(\theta_k)$; 3. 求解 $Q(\theta|\theta_k)$ 的最优值 $\theta_{k+1}=\arg\min_\theta Q(
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。