java pgp 加密_java – 如何解密签名的pgp加密文件?
如何使用BouncyCastle Java API解密和验证使用PGP加密的文件?
解决方法:
加密代码:
private static void encryptFile(OutputStream out, String fileName, PGPPublicKey encKey, PGPSecretKey pgpSec, boolean armor, boolean withIntegrityCheck, char[] pass) throws IOException, NoSuchProviderException {
if (armor) {
out = new ArmoredOutputStream(out);
}
try {
PGPEncryptedDataGenerator encGen =
new PGPEncryptedDataGenerator(
new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(
new SecureRandom())
.setProvider("BC"));
encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider("BC"));
OutputStream encryptedOut = encGen.open(out, new byte[BUFFER_SIZE]);
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
OutputStream compressedData = comData.open(encryptedOut);
//OutputStream compressedData = encryptedOut;
PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(
new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
PGPSignatureGenerator sGen = new PGPSignatureGenerator(new JcaPGPContentSignerBuilder(
pgpSec.getPublicKey().getAlgorithm(), PGPUtil.SHA1).setProvider("BC"));
sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
Iterator it = pgpSec.getPublicKey().getUserIDs();
if (it.hasNext()) {
PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
spGen.setSignerUserID(false, (String) it.next());
sGen.setHashedSubpackets(spGen.generate());
}
//BCPGOutputStream bOut = new BCPGOutputStream(compressedData);
sGen.generateOnePassVersion(false).encode(compressedData); // bOut
File file = new File(fileName);
PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
OutputStream lOut = lGen.open(compressedData, PGPLiteralData.BINARY, file.getName(), new Date(),
new byte[BUFFER_SIZE]); //bOut
FileInputStream fIn = new FileInputStream(file);
int ch;
while ((ch = fIn.read()) >= 0) {
lOut.write(ch);
sGen.update((byte) ch);
}
fIn.close();
lOut.close();
lGen.close();
sGen.generate().encode(compressedData);
//bOut.close();
comData.close();
compressedData.close();
encryptedOut.close();
encGen.close();
if (armor) {
out.close();
}
} catch (PGPException e) {
System.err.println(e);
if (e.getUnderlyingException() != null) {
e.getUnderlyingException().printStackTrace();
}
} catch (SignatureException e) {
System.err.println(e);
}
}
解密代码:
public static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, OutputStream fOut, InputStream publicKeyIn) throws IOException, NoSuchProviderException, SignatureException,
PGPException {
in = PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc;
Object o = pgpF.nextObject();
//
// the first object might be a PGP marker packet.
//
if (o instanceof PGPEncryptedDataList) {
enc = (PGPEncryptedDataList) o;
} else {
enc = (PGPEncryptedDataList) pgpF.nextObject();
}
//
// find the secret key
//
Iterator> it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = PGPTools.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
}
if (sKey == null) {
throw new IllegalArgumentException("secret key for message not found.");
}
InputStream clear = pbe.getDataStream(
new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
PGPObjectFactory plainFact = new PGPObjectFactory(clear);
Object message = null;
PGPOnePassSignatureList onePassSignatureList = null;
PGPSignatureList signatureList = null;
PGPCompressedData compressedData = null;
message = plainFact.nextObject();
ByteArrayOutputStream actualOutput = new ByteArrayOutputStream();
while (message != null) {
log.trace(message.toString());
if (message instanceof PGPCompressedData) {
compressedData = (PGPCompressedData) message;
plainFact = new PGPObjectFactory(compressedData.getDataStream());
message = plainFact.nextObject();
}
if (message instanceof PGPLiteralData) {
// have to read it and keep it somewhere.
Streams.pipeAll(((PGPLiteralData) message).getInputStream(), actualOutput);
} else if (message instanceof PGPOnePassSignatureList) {
onePassSignatureList = (PGPOnePassSignatureList) message;
} else if (message instanceof PGPSignatureList) {
signatureList = (PGPSignatureList) message;
} else {
throw new PGPException("message unknown message type.");
}
message = plainFact.nextObject();
}
actualOutput.close();
PGPPublicKey publicKey = null;
byte[] output = actualOutput.toByteArray();
if (onePassSignatureList == null || signatureList == null) {
throw new PGPException("Poor PGP. Signatures not found.");
} else {
for (int i = 0; i < onePassSignatureList.size(); i++) {
PGPOnePassSignature ops = onePassSignatureList.get(0);
log.trace("verifier : " + ops.getKeyID());
PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(
PGPUtil.getDecoderStream(publicKeyIn));
publicKey = pgpRing.getPublicKey(ops.getKeyID());
if (publicKey != null) {
ops.init(new JcaPGPContentVerifierBuilderProvider().setProvider("BC"), publicKey);
ops.update(output);
PGPSignature signature = signatureList.get(i);
if (ops.verify(signature)) {
Iterator> userIds = publicKey.getUserIDs();
while (userIds.hasNext()) {
String userId = (String) userIds.next();
log.trace("Signed by {}", userId);
}
log.trace("Signature verified");
} else {
throw new SignatureException("Signature verification failed");
}
}
}
}
if (pbe.isIntegrityProtected() && !pbe.verify()) {
throw new PGPException("Data is integrity protected but integrity is lost.");
} else if (publicKey == null) {
throw new SignatureException("Signature not found");
} else {
fOut.write(output);
fOut.flush();
fOut.close();
}
}
作为参考,这是PGPTools.findSecretKey所做的:
public static PGPPrivateKey findSecretKey(InputStream keyIn, long keyID, char[] pass)
throws IOException, PGPException {
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) return null;
PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass);
return pgpSecKey.extractPrivateKey(decryptor);
}
标签:java,cryptography,encryption,bouncycastle,pgp
来源: https://codeday.me/bug/20190614/1236398.html
java pgp 加密_java – 如何解密签名的pgp加密文件?相关推荐
- java 图片加密_java 对视频和图片进行加密解密[转]
是时候回到文件加密与解密的具体实现这个主题上来了.后续的举例均采用图片(包括GIF动画)类型,而其他类型资源的实现原理相同,就不一一给出了.首先来看对一幅JPG类型图片进行异或加密的Java实现,由于 ...
- java 消息摘要_java – 使用BouncyCastle签名消息摘要
在C#的那一刻,我正在签署这样的挑战: RSACryptoServiceProvider rsa; RSAPKCS1SignatureFormatter RSAFormatter = new RSAP ...
- php sha256加密介绍,php SHA256WithRSA签名验签加密解密
使用: $pri_key ="": $pub_key = ""; $char = '方方块儿';//要加密的字符 $sign = $this->RsaEn ...
- java url内容加密_java URLEncoder和URLDecoder 网络数据传输加密
/* 网页中的表单使用POST方法提交时,数据内容的类型是application/x-www-form-urlencoded,这种类型会: 1.字符"a"-"z" ...
- JAVA ftps设置_Java使用JSCH实现对FTPS服务器文件操作
SFTP是Secure File Transfer Protocol的缩写,安全文件传送协议.可以为传输文件提供一种安全的加密方法.SFTP 为 SSH的一部份,是一种传输文件到服务器的安全方式.SF ...
- java校验文件格式_java验证文件格式工具类(获取文件真实格式)
, String>();privateVerifyFileType(){} static{ getAllFileType();//初始化文件类型信息} /*** Discription:[get ...
- java ssh文件下载_Java使用SSH从远程服务器下载文件
前言 Telnet.FTP.POP3在网络传输的过程中都是采用明文,容易被监听或者遭到到man-in-the-middle的攻击方式攻击.而SSH为远程登陆会话和其他的网络服务提供安全协议,通过加密数 ...
- java 指定文件格式_java删除指定目录下指定格式文件的方法
本文实例为大家分享了java删除指定目录下指定格式文件的具体代码,供大家参考,具体内容如下 正在看疯狂java讲义这本书,发现源码中有我不需要的class文件,想批量把它删除 代码如下: import ...
- java文件名特殊字符_Java 8:用名字读取特殊字符的文件
我试图在Linux系统上读取名称中包含特殊字符的文件.我对操作系统没有任何控制权. 我试过使用IO和NIO.我不断地 java.nio.file.invalidPathException:格式错误的输 ...
最新文章
- RHEL7 单独安装图形 X11
- 成功解决Future Warning: The sklearn.neighbors.dist_metrics module is deprecated in version 0.22 and wil
- 网络编程释疑之:单台服务器上的并发TCP连接数可以有多少
- 靠刷算法题,真的可以刷进大厂吗?
- oracle 并行用索引,分区索引并行导致的性能问题
- Docker 安装Centos,Tomcat,Jdk等相关的自定义(Dockerfile)镜像
- 芯片大神Jim Keller从特斯拉离职,转投“宿敌”英特尔
- c++ 退出函数_UCOSIII源码分析之——bsp_os.c文件分析
- HashTable和HashMap的区别详解(转)
- Atiitt attilax掌握的前后技术放在简历里面.docx
- 遗传算法GA优化BPNN
- 用evo工具分析ORB-SLAM2运行TUM,KITTI,EuRoC数据集轨迹
- python识别图片文字
- 面向对象:不要热情,不要高冷,只要37度的温暖
- 分析各渠道广告,建立评分模型以及找到优质渠道的特性
- 中国大学MOOC胡浩基的机器学习第二章(支持向量机)兵王问题python版本——在python上初步使用libsvm
- 统计系列(二)常见的概率分布
- PLSQL无客户端连接ORACLE
- 基于C语言的数据结构课程设计(学生管理系统、停车场管理、家谱管理、校园导航系统)
- 笔记本电脑一开盖就开机?