Java 如何使用bouncycastle pgp加密字符串/流而不从文件开始
我需要使用bouncycastle提供程序使用pgp加密流。我能找到的所有例子都是关于获取一个纯文本文件并对其进行加密的,但是我没有一个文件,而且绝对不要将纯文本写入磁盘,这一点很重要 我看到的大多数方法都是使用 PGPUtil.writeFileToLiteralData,它希望传入纯文本。我宁愿传入字节[]或输入流 有人能给我举个例子吗Java 如何使用bouncycastle pgp加密字符串/流而不从文件开始,java,bouncycastle,pgp,Java,Bouncycastle,Pgp,我需要使用bouncycastle提供程序使用pgp加密流。我能找到的所有例子都是关于获取一个纯文本文件并对其进行加密的,但是我没有一个文件,而且绝对不要将纯文本写入磁盘,这一点很重要 我看到的大多数方法都是使用 PGPUtil.writeFileToLiteralData,它希望传入纯文本。我宁愿传入字节[]或输入流 有人能给我举个例子吗 从字符串/字节[]/inputstream开始 将所述字符串/字节[]加密为我可以写入文件的输出字符串 从输入流解密 以防其他人偶然发现这一点,并希望得
- 从字符串/字节[]/inputstream开始
- 将所述字符串/字节[]加密为我可以写入文件的输出字符串
- 从输入流解密
package com.common.security.pgp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
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.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPObjectFactory;
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.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
/**
* Simple routine to encrypt and decrypt using a Public and Private key with passphrase. This service
* routine provides the basic PGP services between byte arrays.
*
*/
public class PgpEncryption {
private static PGPPrivateKey findSecretKey(
PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
throws PGPException, NoSuchProviderException {
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) {
return null;
}
return pgpSecKey.extractPrivateKey(pass, "BC");
}
/**
* decrypt the passed in message stream
*
* @param encrypted
* The message to be decrypted.
* @param passPhrase
* Pass phrase (key)
*
* @return Clear text as a byte array. I18N considerations are not handled
* by this routine
* @exception IOException
* @exception PGPException
* @exception NoSuchProviderException
*/
public static byte[] decrypt(byte[] encrypted, InputStream keyIn, char[] password)
throws IOException, PGPException, NoSuchProviderException {
InputStream in = new ByteArrayInputStream(encrypted);
in = PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc = null;
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 = findSecretKey(pgpSec, pbe.getKeyID(), password);
}
if (sKey == null) {
throw new IllegalArgumentException(
"secret key for message not found.");
}
InputStream clear = pbe.getDataStream(sKey, "BC");
PGPObjectFactory pgpFact = new PGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();
pgpFact = new PGPObjectFactory(cData.getDataStream());
PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();
InputStream unc = ld.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int ch;
while ((ch = unc.read()) >= 0) {
out.write(ch);
}
byte[] returnBytes = out.toByteArray();
out.close();
return returnBytes;
}
/**
* Simple PGP encryptor between byte[].
*
* @param clearData
* The test to be encrypted
* @param passPhrase
* The pass phrase (key). This method assumes that the key is a
* simple pass phrase, and does not yet support RSA or more
* sophisiticated keying.
* @param fileName
* File name. This is used in the Literal Data Packet (tag 11)
* which is really inly important if the data is to be related to
* a file to be recovered later. Because this routine does not
* know the source of the information, the caller can set
* something here for file name use that will be carried. If this
* routine is being used to encrypt SOAP MIME bodies, for
* example, use the file name from the MIME type, if applicable.
* Or anything else appropriate.
*
* @param armor
*
* @return encrypted data.
* @exception IOException
* @exception PGPException
* @exception NoSuchProviderException
*/
public static byte[] encrypt(byte[] clearData, PGPPublicKey encKey,
String fileName,boolean withIntegrityCheck, boolean armor)
throws IOException, PGPException, NoSuchProviderException {
if (fileName == null) {
fileName = PGPLiteralData.CONSOLE;
}
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
OutputStream out = encOut;
if (armor) {
out = new ArmoredOutputStream(out);
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
PGPCompressedDataGenerator.ZIP);
OutputStream cos = comData.open(bOut); // open it with the final
// destination
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
// we want to generate compressed data. This might be a user option
// later,
// in which case we would pass in bOut.
OutputStream pOut = lData.open(cos, // the compressed output stream
PGPLiteralData.BINARY, fileName, // "filename" to store
clearData.length, // length of clear data
new Date() // current time
);
pOut.write(clearData);
lData.close();
comData.close();
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(),
"BC");
cPk.addMethod(encKey);
byte[] bytes = bOut.toByteArray();
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes); // obtain the actual bytes from the compressed stream
cOut.close();
out.close();
return encOut.toByteArray();
}
private static PGPPublicKey readPublicKey(InputStream in)
throws IOException, PGPException {
in = PGPUtil.getDecoderStream(in);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);
//
// we just loop through the collection till we find a key suitable for
// encryption, in the real
// world you would probably want to be a bit smarter about this.
//
//
// iterate through the key rings.
//
Iterator rIt = pgpPub.getKeyRings();
while (rIt.hasNext()) {
PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
Iterator kIt = kRing.getPublicKeys();
while (kIt.hasNext()) {
PGPPublicKey k = (PGPPublicKey) kIt.next();
if (k.isEncryptionKey()) {
return k;
}
}
}
throw new IllegalArgumentException(
"Can't find encryption key in key ring.");
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
byte[] original = "Hello world".getBytes();
System.out.println("Starting PGP test");
FileInputStream pubKey = new FileInputStream("/Users/me/pub.key");
byte[] encrypted = encrypt(original, readPublicKey(pubKey), null,
true, true);
FileOutputStream dfis = new FileOutputStream("/Users/me/enc.asc");
dfis.write(encrypted);
dfis.close();
byte[] encFromFile = getBytesFromFile(new File("/Users/me/enc.asc"));
FileInputStream secKey = new FileInputStream("/Users/me/sec.key");
System.out.println("\nencrypted data = '" + new String(encrypted) + "'");
byte[] decrypted = decrypt(encFromFile, secKey, "passphrase".toCharArray());
System.out.println("\ndecrypted data = '" + new String(decrypted) + "'");
}
}
package com.common.security.pgp;
导入java.io.ByteArrayInputStream;
导入java.io.ByteArrayOutputStream;
导入java.io.File;
导入java.io.FileInputStream;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.security.NoSuchProviderException;
导入java.security.SecureRandom;
导入java.security.security;
导入java.util.Date;
导入java.util.Iterator;
导入org.bouncycastle.bcpg.ArmoredOutputStream;
导入org.bouncycastle.jce.provider.BouncyCastleProvider;
导入org.bouncycastle.openpgp.PGPCompressedData;
导入org.bouncycastle.openpgp.pgpccompressedatagenerator;
导入org.bouncycastle.openpgp.PGPEncryptedData;
导入org.bouncycastle.openpgp.pgpencryptedatagenerator;
导入org.bouncycastle.openpgp.pgpencryptedatalist;
导入org.bouncycastle.openpgp.PGPException;
导入org.bouncycastle.openpgp.PGPLiteralData;
导入org.bouncycastle.openpgp.PGPLiteralDataGenerator;
导入org.bouncycastle.openpgp.PGPObjectFactory;
导入org.bouncycastle.openpgp.PGPPrivateKey;
导入org.bouncycastle.openpgp.PGPPublicKey;
导入org.bouncycastle.openpgp.pgppubliceEncryptedData;
导入org.bouncycastle.openpgp.PGPPublicKeyRing;
导入org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
导入org.bouncycastle.openpgp.PGPSecretKey;
导入org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
导入org.bouncycastle.openpgp.PGPUtil;
/**
*使用带有密码短语的公钥和私钥进行加密和解密的简单例程。这项服务
*例程提供字节数组之间的基本PGP服务。
*
*/
公共类密码选项{
私有静态PGPPrivateKey findSecretKey(
PGPSecretKeyRingCollection pgpSec,长密钥ID,字符[]传递)
抛出PGPEException,无此ProviderException{
PGPSecretKey pgpSecKey=pgpSec.getSecretKey(keyID);
如果(pgpSecKey==null){
返回null;
}
返回pgpSecKey.extractPrivateKey(通过“BC”);
}
/**
*解密传入的消息流
*
*@param加密
*要解密的消息。
*@param密码短语
*通行短语(关键)
*
*@以字节数组形式返回明文。不处理I18N注意事项
*按惯例
*@exception-IOException
*@exception pgpeexception
*@exception NoSuchProviderException
*/
公共静态字节[]解密(字节[]加密,输入流密钥,字符[]密码)
抛出IOException、PGPEException、NoSuchProviderException{
InputStream in=新的ByteArrayInputStream(加密);
in=PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF=新的PGPObjectFactory(in);
PGPEncryptedDataList enc=null;
对象o=pgpF.nextObject();
//
//第一个对象可能是PGP标记包。
//
if(o PGPEncryptedDataList的实例){
enc=(pGpencryptedatalist)o;
}否则{
enc=(pgpencryptedatalist)pgpF.nextObject();
}
//
//找到密匙
//
迭代器it=enc.getEncryptedDataObjects();
PGPPrivateKey sKey=null;
PGPPublicKeyEncryptedData pbe=null;
PGPSecretKeyRingCollection pgpSec=新的PGPSecretKeyRingCollection(
PGPUtil.getDecoderStream(keyIn));
while(sKey==null&&it.hasNext()){
pbe=(PGPPublicKeyEncryptedData)it.next();
sKey=findSecretKey(pgpSec,pbe.getKeyID(),密码);
}
if(sKey==null){
抛出新的IllegalArgumentException(
“未找到邮件的密钥。”);
}
InputStream clear=pbe.getDataStream(sKey,“BC”);
PGPObjectFactory pgpFact=新PGPObjectFactory(清除);
PGPCompressedData cData=(PGPCompressedData)pgpFact.nextObject();
pgpFact=新的PGPObjectFactory(cData.getDataStream());
PGPLiteralData ld=(PGPLiteralData)pgpFact.nextObject();
InputStream unc=ld.getInputStream();
ByteArrayOutputStream out=新建ByteArrayOutputStream();
int-ch;
而((ch=unc.read())>=0){
out.write(ch);
}
byte[]returnBytes=out.toByteArray();
out.close();
返回字节;
}
/**
*字节[]之间的简单PGP加密程序。
*
*@param clearData
*要加密的测试
*@param密码短语
*密码短语(键)。此方法假定键是
*简单的密码短语,不支持RSA或更多
*诡辩的键控。
*@param文件名
*文件名。这用于文本数据包(标记11)
*如果数据要与
*稍后要恢复的文件。因为此例程
*知道信息的来源,调用方可以设置
*这里有一些用于文件名的东西,将被携带
*例程被用来加密SOAP
public static void writeFileToLiteralData(OutputStream out,
char fileType, File file, byte[] buffer) throws IOException {
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
OutputStream pOut = lData.open(out, fileType, file.getName(),
new Date(file.lastModified()), buffer);
FileInputStream in = new FileInputStream(file);
byte[] buf = new byte[buffer.length];
int len;
while ((len = in.read(buf)) > 0) {
pOut.write(buf, 0, len);
}
lData.close();
in.close();
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
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.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPObjectFactory;
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.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
/**
* Simple routine to encrypt and decrypt using a Public and Private key with passphrase. This service
* routine provides the basic PGP services between byte arrays.
*
*/
public class PgpEncryption {
public PgpEncryption() {
// Empty constructor
}
private static PGPPrivateKey findSecretKey(
PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
throws PGPException, NoSuchProviderException {
PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);
if (pgpSecKey == null) {
return null;
}
return pgpSecKey.extractPrivateKey(pass, "BC");
}
/**
* decrypt the passed in message stream
*
* @param encrypted
* The message to be decrypted.
* @param passPhrase
* Pass phrase (key)
*
* @return Clear text as a byte array. I18N considerations are not handled
* by this routine
* @exception IOException
* @exception PGPException
* @exception NoSuchProviderException
*/
public static byte[] decrypt(byte[] encrypted, InputStream keyIn, char[] password)
throws IOException, PGPException, NoSuchProviderException {
InputStream in = new ByteArrayInputStream(encrypted);
in = PGPUtil.getDecoderStream(in);
PGPObjectFactory pgpF = new PGPObjectFactory(in);
PGPEncryptedDataList enc = null;
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 = findSecretKey(pgpSec, pbe.getKeyID(), password);
}
if (sKey == null) {
throw new IllegalArgumentException(
"secret key for message not found.");
}
InputStream clear = pbe.getDataStream(sKey, "BC");
PGPObjectFactory pgpFact = new PGPObjectFactory(clear);
PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();
pgpFact = new PGPObjectFactory(cData.getDataStream());
PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();
InputStream unc = ld.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int ch;
while ((ch = unc.read()) >= 0) {
out.write(ch);
}
byte[] returnBytes = out.toByteArray();
out.close();
return returnBytes;
}
/**
* Simple PGP encryptor between byte[].
*
* @param clearData
* The test to be encrypted
* @param passPhrase
* The pass phrase (key). This method assumes that the key is a
* simple pass phrase, and does not yet support RSA or more
* sophisiticated keying.
* @param fileName
* File name. This is used in the Literal Data Packet (tag 11)
* which is really inly important if the data is to be related to
* a file to be recovered later. Because this routine does not
* know the source of the information, the caller can set
* something here for file name use that will be carried. If this
* routine is being used to encrypt SOAP MIME bodies, for
* example, use the file name from the MIME type, if applicable.
* Or anything else appropriate.
*
* @param armor
*
* @return encrypted data.
* @exception IOException
* @exception PGPException
* @exception NoSuchProviderException
*/
public static byte[] encrypt(byte[] clearData, PGPPublicKey encKey,
String fileName,boolean withIntegrityCheck, boolean armor)
throws IOException, PGPException, NoSuchProviderException {
if (fileName == null) {
fileName = PGPLiteralData.CONSOLE;
}
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
OutputStream out = encOut;
if (armor) {
out = new ArmoredOutputStream(out);
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
PGPCompressedDataGenerator.ZIP);
OutputStream cos = comData.open(bOut); // open it with the final
// destination
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
// we want to generate compressed data. This might be a user option
// later,
// in which case we would pass in bOut.
OutputStream pOut = lData.open(cos, // the compressed output stream
PGPLiteralData.BINARY, fileName, // "filename" to store
clearData.length, // length of clear data
new Date() // current time
);
pOut.write(clearData);
lData.close();
comData.close();
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
PGPEncryptedData.CAST5, withIntegrityCheck, new SecureRandom(),
"BC");
cPk.addMethod(encKey);
byte[] bytes = bOut.toByteArray();
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes); // obtain the actual bytes from the compressed stream
cOut.close();
out.close();
return encOut.toByteArray();
}
private static PGPPublicKey readPublicKey(InputStream in)
throws IOException, PGPException {
in = PGPUtil.getDecoderStream(in);
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);
//
// we just loop through the collection till we find a key suitable for
// encryption, in the real
// world you would probably want to be a bit smarter about this.
//
//
// iterate through the key rings.
//
Iterator rIt = pgpPub.getKeyRings();
while (rIt.hasNext()) {
PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
Iterator kIt = kRing.getPublicKeys();
while (kIt.hasNext()) {
PGPPublicKey k = (PGPPublicKey) kIt.next();
if (k.isEncryptionKey()) {
return k;
}
}
}
throw new IllegalArgumentException(
"Can't find encryption key in key ring.");
}
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
public static String encryptToFile(String inputStr, String keyFile, String outFile) throws Exception {
Security.addProvider(new BouncyCastleProvider());
byte[] original = inputStr.getBytes();
FileInputStream pubKey = new FileInputStream(keyFile);
byte[] encrypted = encrypt(original, readPublicKey(pubKey), null,
true, true);
FileOutputStream dfis = new FileOutputStream(outFile);
dfis.write(encrypted);
dfis.close();
return new String(encrypted);
}
public static String decryptFromFile(String passphrase, String keyFile, String inputFile) throws Exception {
Security.addProvider(new BouncyCastleProvider());
byte[] encFromFile = getBytesFromFile(new File(inputFile));
FileInputStream secKey = new FileInputStream(keyFile);
byte[] decrypted = decrypt(encFromFile, secKey, passphrase.toCharArray());
return new String(decrypted);
}
public static void main(String[] args) throws Exception {
String encrypted = encryptToFile("Hello world","pub.asc","enc.asc");
System.out.println("\nencrypted data = '" + new String(encrypted) + "'");
String decrypted = decryptFromFile("open sesame", "secret.asc", "enc.asc");
System.out.println("\ndecrypted data = '" + decrypted + "'");
}
}
private static void writeBytesToLiteralData(OutputStream out,
char fileType, String name, byte[] bytes) throws IOException {
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
OutputStream pOut = lData.open(out, fileType, name,bytes.length, new Date());
pOut.write(bytes);
}
// the string you will like to encrypt
byte[] original = "I love programming".getBytes();
// KeyProvider.PUBLIC_KEY this is just a string holding your public key. you can have it stored in memory or something.
byte[] encrypted = encrypt(original, readPublicKey(new ByteArrayInputStream(KeyProvider.PUBLIC_KEY.getBytes())), null, true, true);
System.out.println(new String(encrypted)); // this will output your encrypted message
//encryted here is the encrypted string in byte array you will like to decrypt and also the KeyProvider.PRIVATE_KEY is string holding your private key
byte[] decrypted = decrypt(encrypted, new ByteArrayInputStream(KeyProvider.PRIVATE_KEY.getBytes()), "".toCharArray());
System.out.println(new String(decrypted)); //output the decrypted message
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Date;
import java.util.Iterator;
public class PgpHelper {
public static byte[] encrypt(String fileName, String content, String pgpPublicKey) throws IOException, PGPException, NoSuchProviderException {
Security.addProvider(new BouncyCastleProvider());
ByteArrayOutputStream zipOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator zipData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
OutputStream zipPacket = new PGPLiteralDataGenerator()
.open(zipData.open(zipOut), PGPLiteralData.BINARY, fileName, content.length(), new Date());
zipPacket.write(content.getBytes(StandardCharsets.UTF_8));
zipPacket.close();
zipData.close();
byte[] zipBytes = zipOut.toByteArray();
zipOut.close();
PGPEncryptedDataGenerator encryptor = new PGPEncryptedDataGenerator(
PGPEncryptedData.CAST5, true, new SecureRandom(), "BC");
InputStream keyIn = new ByteArrayInputStream(pgpPublicKey.getBytes());
encryptor.addMethod(readPublicKey(keyIn));
keyIn.close();
ByteArrayOutputStream encryptOut = new ByteArrayOutputStream();
OutputStream encryptPacket = encryptor.open(encryptOut, zipBytes.length);
encryptPacket.write(zipBytes);
encryptPacket.close();
byte[] encryptBytes = encryptOut.toByteArray();
encryptOut.close();
return encryptBytes;
}
@SuppressWarnings("unchecked")
private static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(in));
Iterator<PGPPublicKeyRing> itKeyRings = pgpPub.getKeyRings();
while (itKeyRings.hasNext()) {
PGPPublicKeyRing keyRing = itKeyRings.next();
Iterator<PGPPublicKey> itKeys = keyRing.getPublicKeys();
while (itKeys.hasNext()) {
PGPPublicKey key = itKeys.next();
if (key.isEncryptionKey()) {
return key;
}
}
}
throw new IllegalArgumentException("Can't find encryption key in key ring.");
}
}