Java Bouncy Castle加密负载来自SAP PI 问题
我正在使用Bouncy Castle java使用PGP加密文件。该程序旨在运行到SAP PI 7.0中。当我对解密程序运行PI的输出(加密文件)时,我得到一个空的解密文件,没有错误 因此,我尝试在Eclipse中使用相同的参数加密相同的源文件。这一次,我能够正确地解密输出,以检索我的原始文件。相同的代码,相同的输入 在某些时候,我注意到PI输出比Eclipse的输出短几个字节(通常为32字节)。我认为这就是解密输出为空而没有错误的原因。我不知道加密文件中可能缺少什么,因为两条PGP消息具有相同的形状 有没有关于我如何修理它的建议?是否缺少PGP消息的一部分?我是否错过了PI环境中的库或配置点 技术细节 弹跳城堡Java Bouncy Castle加密负载来自SAP PI 问题,java,sap,bouncycastle,sap-xi,sap-pi,Java,Sap,Bouncycastle,Sap Xi,Sap Pi,我正在使用Bouncy Castle java使用PGP加密文件。该程序旨在运行到SAP PI 7.0中。当我对解密程序运行PI的输出(加密文件)时,我得到一个空的解密文件,没有错误 因此,我尝试在Eclipse中使用相同的参数加密相同的源文件。这一次,我能够正确地解密输出,以检索我的原始文件。相同的代码,相同的输入 在某些时候,我注意到PI输出比Eclipse的输出短几个字节(通常为32字节)。我认为这就是解密输出为空而没有错误的原因。我不知道加密文件中可能缺少什么,因为两条PGP消息具有相同
- 版本1.47
- JDK:1.3
- Jar下载地址:jce-jdk13-147.Jar,bcpg-jdk13-147.Jar
- Java:1.6.0_45
- 操作系统:Windows7SP1
- JDK版本:1.3
- PI版本:7.0
- Java运行时:Java(TM)2运行时环境,标准版(版本=1.4.2_14-b05)
- Java虚拟机:Java热点(TM)64位服务器虚拟机(版本=1.4.2_14-b05)
- 操作系统:Windows 2003(版本=5.2,arch=amd64)
- JDK版本:1.3
public class BcPGP {
private static final int BUFFER_SIZE = 1 << 16; // should always be power of
// 2
private static final int KEY_FLAGS = 27;
private static final int[] MASTER_KEY_CERTIFICATION_TYPES = new int[] { PGPSignature.POSITIVE_CERTIFICATION,
PGPSignature.CASUAL_CERTIFICATION, PGPSignature.NO_CERTIFICATION, PGPSignature.DEFAULT_CERTIFICATION };
public static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {
PGPPublicKeyRingCollection keyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(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.
//
PGPPublicKey publicKey = null;
//
// iterate through the key rings.
//
Iterator rIt = keyRingCollection.getKeyRings();
while (publicKey == null && rIt.hasNext()) {
PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
Iterator kIt = kRing.getPublicKeys();
while (publicKey == null && kIt.hasNext()) {
PGPPublicKey key = (PGPPublicKey) kIt.next();
if (key.isEncryptionKey()) {
publicKey = key;
}
}
}
if (publicKey == null) {
throw new IllegalArgumentException("Can't find public key in the key ring.");
}
if (!isForEncryption(publicKey)) {
throw new IllegalArgumentException("KeyID " + publicKey.getKeyID() + " not flagged for encryption.");
}
return publicKey;
}
public static PGPSecretKey readSecretKey(InputStream in) throws IOException, PGPException {
PGPSecretKeyRingCollection keyRingCollection = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(in));
//
// We just loop through the collection till we find a key suitable for
// signing.
// In the real world you would probably want to be a bit smarter about
// this.
//
PGPSecretKey secretKey = null;
Iterator rIt = keyRingCollection.getKeyRings();
while (secretKey == null && rIt.hasNext()) {
PGPSecretKeyRing keyRing = (PGPSecretKeyRing) rIt.next();
Iterator kIt = keyRing.getSecretKeys();
while (secretKey == null && kIt.hasNext()) {
PGPSecretKey key = (PGPSecretKey) kIt.next();
if (key.isSigningKey()) {
secretKey = key;
}
}
}
// Validate secret key
if (secretKey == null) {
throw new IllegalArgumentException("Can't find private key in the key ring.");
}
if (!secretKey.isSigningKey()) {
throw new IllegalArgumentException("Private key does not allow signing.");
}
if (secretKey.getPublicKey().isRevoked()) {
throw new IllegalArgumentException("Private key has been revoked.");
}
if (!hasKeyFlags(secretKey.getPublicKey(), KeyFlags.SIGN_DATA)) {
throw new IllegalArgumentException("Key cannot be used for signing.");
}
return secretKey;
}
/**
* Load a secret key ring collection from keyIn and find the private key
* corresponding to keyID if it exists.
*
* @param keyIn
* input stream representing a key ring collection.
* @param keyID
* keyID we want.
* @param pass
* passphrase to decrypt secret key with.
* @return
* @throws IOException
* @throws PGPException
* @throws NoSuchProviderException
*/
public static PGPPrivateKey findPrivateKey(InputStream keyIn, long keyID, char[] pass) throws IOException, PGPException,
NoSuchProviderException {
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
return findPrivateKey(pgpSec.getSecretKey(keyID), pass);
}
/**
* Load a secret key and find the private key in it
*
* @param pgpSecKey
* The secret key
* @param pass
* passphrase to decrypt secret key with
* @return
* @throws PGPException
*/
public static PGPPrivateKey findPrivateKey(PGPSecretKey pgpSecKey, char[] pass) throws PGPException {
if (pgpSecKey == null)
return null;
PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass);
return pgpSecKey.extractPrivateKey(decryptor);
}
/**
* decrypt the passed in message stream
*/
public static void decryptFile(InputStream in, OutputStream out, InputStream keyIn, char[] passwd) throws Exception {
Security.addProvider(new BouncyCastleProvider());
in = org.bouncycastle.openpgp.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;
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = findPrivateKey(keyIn, pbe.getKeyID(), passwd);
}
if (sKey == null) {
throw new IllegalArgumentException("Secret key for message not found.");
}
InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey));
PGPObjectFactory plainFact = new PGPObjectFactory(clear);
Object message = plainFact.nextObject();
if (message instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) message;
PGPObjectFactory pgpFact = new PGPObjectFactory(cData.getDataStream());
message = pgpFact.nextObject();
}
if (message instanceof PGPLiteralData) {
PGPLiteralData ld = (PGPLiteralData) message;
InputStream unc = ld.getInputStream();
int ch;
while ((ch = unc.read()) >= 0) {
out.write(ch);
}
} else if (message instanceof PGPOnePassSignatureList) {
throw new PGPException("Encrypted message contains a signed message - not literal data.");
} else {
throw new PGPException("Message is not a simple encrypted file - type unknown.");
}
if (pbe.isIntegrityProtected()) {
if (!pbe.verify()) {
throw new PGPException("Message failed integrity check");
}
}
}
public static void encryptFile(OutputStream out, InputStream is, PGPPublicKey encKey, boolean armor,
boolean withIntegrityCheck, int compressType, int encryptType) throws IOException, NoSuchProviderException,
PGPException {
System.out.println("Add BouncyCastleProvider");
Security.addProvider(new BouncyCastleProvider());
if (armor) {
out = new ArmoredOutputStream(out);
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(compressType);
// setup temp file to hold source data - this is necessary when using
// PGPUtil.writeFileToLiteralData which uses a file
System.out.println("Creating a temp file...");
File tempfile = File.createTempFile("pgp", null);
FileOutputStream fos = new FileOutputStream(tempfile);
int read = 0;
byte[] inBytes = new byte[1024];
while ((read = is.read(inBytes)) != -1) {
fos.write(inBytes, 0, read);
}
fos.flush();
fos.close();
System.out.println("Temp file created at ");
System.out.println(tempfile.getAbsolutePath());
PGPUtil.writeFileToLiteralData(comData.open(bOut), PGPLiteralData.BINARY, new File(tempfile.getAbsolutePath()));
comData.close();
BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(encryptType);
dataEncryptor.setWithIntegrityPacket(withIntegrityCheck);
dataEncryptor.setSecureRandom(new SecureRandom());
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(encKey));
byte[] outBytes = bOut.toByteArray();
OutputStream cOut = encryptedDataGenerator.open(out, outBytes.length);
cOut.write(outBytes);
cOut.close();
out.close();
System.out.println("data encrypted");
}
public static void signEncryptFile(OutputStream out, String fileName, PGPPublicKey publicKey, PGPSecretKey secretKey,
String password, boolean armor, boolean withIntegrityCheck) throws Exception {
// Initialize Bouncy Castle security provider
Provider provider = new BouncyCastleProvider();
Security.addProvider(provider);
if (armor) {
out = new ArmoredOutputStream(out);
}
BcPGPDataEncryptorBuilder dataEncryptor = new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.TRIPLE_DES);
dataEncryptor.setWithIntegrityPacket(withIntegrityCheck);
dataEncryptor.setSecureRandom(new SecureRandom());
PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(dataEncryptor);
encryptedDataGenerator.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(publicKey));
OutputStream encryptedOut = encryptedDataGenerator.open(out, new byte[BcPGP.BUFFER_SIZE]);
// Initialize compressed data generator
PGPCompressedDataGenerator compressedDataGenerator = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZIP);
OutputStream compressedOut = compressedDataGenerator.open(encryptedOut, new byte[BcPGP.BUFFER_SIZE]);
// Initialize signature generator
PGPPrivateKey privateKey = findPrivateKey(secretKey, password.toCharArray());
PGPContentSignerBuilder signerBuilder = new BcPGPContentSignerBuilder(secretKey.getPublicKey().getAlgorithm(),
HashAlgorithmTags.SHA1);
PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(signerBuilder);
signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, privateKey);
boolean firstTime = true;
Iterator it = secretKey.getPublicKey().getUserIDs();
while (it.hasNext() && firstTime) {
PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
spGen.setSignerUserID(false, (String) it.next());
signatureGenerator.setHashedSubpackets(spGen.generate());
// Exit the loop after the first iteration
firstTime = false;
}
signatureGenerator.generateOnePassVersion(false).encode(compressedOut);
// Initialize literal data generator
PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
OutputStream literalOut = literalDataGenerator.open(compressedOut, PGPLiteralData.BINARY, fileName, new Date(),
new byte[BcPGP.BUFFER_SIZE]);
// Main loop - read the "in" stream, compress, encrypt and write to the
// "out" stream
FileInputStream in = new FileInputStream(fileName);
byte[] buf = new byte[BcPGP.BUFFER_SIZE];
int len;
while ((len = in.read(buf)) > 0) {
literalOut.write(buf, 0, len);
signatureGenerator.update(buf, 0, len);
}
in.close();
literalDataGenerator.close();
// Generate the signature, compress, encrypt and write to the "out"
// stream
signatureGenerator.generate().encode(compressedOut);
compressedDataGenerator.close();
encryptedDataGenerator.close();
if (armor) {
out.close();
}
}
// public static boolean verifyFile(InputStream in, InputStream keyIn,
// String extractContentFile) throws Exception {
// in = PGPUtil.getDecoderStream(in);
//
// PGPObjectFactory pgpFact = new PGPObjectFactory(in);
// PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject();
//
// pgpFact = new PGPObjectFactory(c1.getDataStream());
//
// PGPOnePassSignatureList p1 = (PGPOnePassSignatureList)
// pgpFact.nextObject();
//
// PGPOnePassSignature ops = p1.get(0);
//
// PGPLiteralData p2 = (PGPLiteralData) pgpFact.nextObject();
//
// InputStream dIn = p2.getInputStream();
//
// IOUtils.copy(dIn, new FileOutputStream(extractContentFile));
//
// int ch;
// PGPPublicKeyRingCollection pgpRing = new
// PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyIn));
//
// PGPPublicKey key = pgpRing.getPublicKey(ops.getKeyID());
//
// FileOutputStream out = new FileOutputStream(p2.getFileName());
//
// ops.init(new BcPGPContentVerifierBuilderProvider(), key);
//
// while ((ch = dIn.read()) >= 0) {
// ops.update((byte) ch);
// out.write(ch);
// }
//
// out.close();
//
// PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
// return ops.verify(p3.get(0));
// }
/**
* From LockBox Lobs PGP Encryption tools.
* http://www.lockboxlabs.org/content/downloads
*
* I didn't think it was worth having to import a 4meg lib for three methods
*
* @param key
* @return
*/
public static boolean isForEncryption(PGPPublicKey key) {
if (key.getAlgorithm() == PublicKeyAlgorithmTags.RSA_SIGN || key.getAlgorithm() == PublicKeyAlgorithmTags.DSA
|| key.getAlgorithm() == PublicKeyAlgorithmTags.EC || key.getAlgorithm() == PublicKeyAlgorithmTags.ECDSA) {
return false;
}
return hasKeyFlags(key, KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE);
}
/**
* From LockBox Lobs PGP Encryption tools.
* http://www.lockboxlabs.org/content/downloads
*
* I didn't think it was worth having to import a 4meg lib for three methods
*
* @param key
* @return
*/
private static boolean hasKeyFlags(PGPPublicKey encKey, int keyUsage) {
if (encKey.isMasterKey()) {
for (int i = 0; i != BcPGP.MASTER_KEY_CERTIFICATION_TYPES.length; i++) {
for (Iterator eIt = encKey.getSignaturesOfType(BcPGP.MASTER_KEY_CERTIFICATION_TYPES[i]); eIt.hasNext();) {
PGPSignature sig = (PGPSignature) eIt.next();
if (!isMatchingUsage(sig, keyUsage)) {
return false;
}
}
}
} else {
for (Iterator eIt = encKey.getSignaturesOfType(PGPSignature.SUBKEY_BINDING); eIt.hasNext();) {
PGPSignature sig = (PGPSignature) eIt.next();
if (!isMatchingUsage(sig, keyUsage)) {
return false;
}
}
}
return true;
}
/**
* From LockBox Lobs PGP Encryption tools.
* http://www.lockboxlabs.org/content/downloads
*
* I didn't think it was worth having to import a 4meg lib for three methods
*
* @param key
* @return
*/
private static boolean isMatchingUsage(PGPSignature sig, int keyUsage) {
if (sig.hasSubpackets()) {
PGPSignatureSubpacketVector sv = sig.getHashedSubPackets();
if (sv.hasSubpacket(BcPGP.KEY_FLAGS)) {
if ((sv.getKeyFlags() & keyUsage) == 0) {
return false;
}
}
}
return true;
}
}
public class FileCopyPGP {
static final String PUBLIC_KEY_PATH = "D:\\PGP\\public.asc";
static final String PRIVATE_KEY_PATH = "D:\\PGP\\secret.asc";
static final String PASSWORD = "TestPass12345!";
static final String SOURCE_PATH = "D:\\PGP\\run\\Source.txt";
static final String ENCRYPTED_PATH = "D:\\PGP\\run\\Encrypted.txt";
static final String DECRYPTED_PATH = "D:\\PGP\\run\\Decrypted.txt";
public static void encrypt(InputStream is, OutputStream os) {
try {
PGPPublicKey encKey = BcPGP.readPublicKey(new FileInputStream(new File(PUBLIC_KEY_PATH)));
long start = System.currentTimeMillis();
System.out.println("Encryption started");
BcPGP.encryptFile(os, is, encKey, true, true, CompressionAlgorithmTags.UNCOMPRESSED,
SymmetricKeyAlgorithmTags.AES_256);
System.out.println("Encryption ended successfully in " + (System.currentTimeMillis() - start) + "ms");
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (PGPException e) {
System.out.println(e.getMessage());
} catch (NoSuchProviderException e) {
System.out.println(e.getMessage());
}
}
public static void decrypt(InputStream is, OutputStream os) {
try {
long start = System.currentTimeMillis();
System.out.println("Decryption started");
BcPGP.decryptFile(is, os, new FileInputStream(new File(PRIVATE_KEY_PATH)), PASSWORD.toCharArray());
System.out.println("Decryption ended successfully in " + (System.currentTimeMillis() - start) + "ms");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws FileNotFoundException {
encrypt(new FileInputStream(new File(SOURCE_PATH)), new FileOutputStream(new File(ENCRYPTED_PATH)));
decrypt(new FileInputStream(new File(ENCRYPTED_PATH)), new FileOutputStream(new File(DECRYPTED_PATH)));
}
}
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import com.sap.aii.mapping.api.AbstractTrace;
import com.sap.aii.mapping.api.StreamTransformation;
import com.sap.aii.mapping.api.StreamTransformationConstants;
import com.sap.aii.mapping.api.StreamTransformationException;
import com.sap.aii.mapping.value.api.IFIdentifier;
import com.sap.aii.mapping.value.api.IFRequest;
import com.sap.aii.mapping.value.api.IFResponse;
import com.sap.aii.mapping.value.api.XIVMFactory;
import com.sap.aii.mapping.value.api.XIVMService;
public class PGPEncryptor implements StreamTransformation {
private Map param;
private AbstractTrace trace;
private String receiver = null;
private static final String SOURCE_AGENCY = "YOUR_SOURCE_AGENCY";
private static final String SOURCE_SCHEME = "YourKeyPath";
private static final String TARGET_AGENCY = "YOUR_TARGET_AGENCY";
private static final String TARGET_SCHEME = "YourKeyPath";
public void setParameter(Map arg0) {
param = arg0;
trace = (AbstractTrace) param.get(StreamTransformationConstants.MAPPING_TRACE);
receiver = (String) param.get(StreamTransformationConstants.RECEIVER_SERVICE);
}
public void execute(InputStream in, OutputStream out) throws StreamTransformationException {
try {
IFIdentifier sourceIdentifier = XIVMFactory.newIdentifier(SOURCE_AGENCY, SOURCE_SCHEME);
IFIdentifier targetIdentifier = XIVMFactory.newIdentifier(TARGET_AGENCY, TARGET_SCHEME);
IFRequest request = XIVMFactory.newRequest(sourceIdentifier, targetIdentifier, receiver);
trace.addInfo("Value Mapping lookup value: " + receiver);
IFResponse response = XIVMService.executeMapping(request);
String encKey;
if (response.hasTargetValues()) {
encKey = response.getSingleTargetValue();
trace.addInfo("Using key path: " + encKey);
} else {
trace.addInfo("Value Mapping lookup parameters");
trace.addInfo("Source");
trace.addInfo("Context: " + sourceIdentifier.getContext() + ", Agency: " + SOURCE_AGENCY + ", Scheme: "
+ SOURCE_SCHEME);
trace.addInfo("Target");
trace.addInfo("Context: " + targetIdentifier.getContext() + ", Agency: " + TARGET_AGENCY + ", Scheme: "
+ TARGET_SCHEME);
trace.addInfo("Value: " + receiver);
throw new StreamTransformationException("Public key not found.");
}
// Encrypt the message
long start = System.currentTimeMillis();
trace.addInfo("Encryption started");
new PGPCrypto().encrypt(encKey, in, out, trace);
trace.addInfo("Encryption ended successfully in " + (System.currentTimeMillis() - start) + "ms");
} catch (Exception e) {
trace.addInfo(e.getMessage());
}
}
}
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Date;
import java.util.Iterator;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
import org.bouncycastle.openpgp.PGPUtil;
import com.sap.aii.mapping.api.AbstractTrace;
public class PGPCrypto {
public void encrypt(String publicKeyPath, InputStream in, OutputStream out, AbstractTrace trace) throws Exception {
try {
encrypt(publicKeyPath, inputStreamToString(in), out, trace);
} catch (Exception e) {
trace.addInfo(e.getMessage());
throw new Exception(e.toString());
}
}
public void encrypt(String publicKeyPath, String inString, OutputStream out, AbstractTrace trace) throws Exception {
try {
Security.addProvider(new BouncyCastleProvider());
InputStream keyStream = new FileInputStream(publicKeyPath);
// Get Publik key
PGPPublicKey key = readPublicKeyFromCol(keyStream);
out = new DataOutputStream(out);
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
writeStringToLiteralData(comData.open(bOut), inString);
comData.close();
// object that encrypts the data
trace.addInfo("Trace1: Going to encrypt the data");
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(),
"BC");
cPk.addMethod(key);
byte[] bytes = bOut.toByteArray();
out = cPk.open(out, bytes.length);
out.write(bytes);
cPk.close();
out.close();
} catch (Exception e) {
trace.addInfo(e.getMessage());
throw new Exception(e.toString());
}
}
private String inputStreamToString(InputStream in) {
// read in stream into string.
StringBuffer buf = new StringBuffer();
try {
InputStreamReader isr = null;
// try UTF-8 conversion
try {
isr = new InputStreamReader(in, "UTF-8");
} catch (UnsupportedEncodingException e) {
// or atleast in natural encoding
isr = new InputStreamReader(in);
}
int c = 0;
while ((c = isr.read()) != -1) {
buf.append((char) c);
}
in.close();
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
return buf.toString();
}
private void writeStringToLiteralData(OutputStream out, String inString) throws IOException {
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
OutputStream pOut = lData.open(out, PGPLiteralData.BINARY, "", inString.length(), new Date());
pOut.write(inString.getBytes());
lData.close();
}
private PGPPublicKey readPublicKeyFromCol(InputStream in) throws Exception {
PGPPublicKeyRing pkRing = null;
PGPPublicKey result = null, key = null;
try {
PGPPublicKeyRingCollection pkCol = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(in));
Iterator it = pkCol.getKeyRings();
while (it.hasNext()) {
pkRing = (PGPPublicKeyRing) it.next();
Iterator pkIt = pkRing.getPublicKeys();
while (pkIt.hasNext()) {
key = (PGPPublicKey) pkIt.next();
if (key.isEncryptionKey()) {
result = key;
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.toString());
}
return result;
}
}