|
import java.io.ByteArrayOutputStream; |
|
import java.io.FileInputStream; |
|
import java.io.IOException; |
|
import java.io.OutputStream; |
|
import java.util.Date; |
|
import java.util.Iterator; |
|
import lombok.val; |
|
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; |
|
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator; |
|
import org.bouncycastle.openpgp.PGPException; |
|
import org.bouncycastle.openpgp.PGPLiteralData; |
|
import org.bouncycastle.openpgp.PGPLiteralDataGenerator; |
|
import org.bouncycastle.openpgp.PGPUtil; |
|
import org.bouncycastle.openpgp.PGPPublicKey; |
|
import org.bouncycastle.openpgp.PGPPublicKeyRing; |
|
import org.bouncycastle.openpgp.PGPPublicKeyRingCollection; |
|
import org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator; |
|
import org.bouncycastle.openpgp.operator.bc.BcPGPDataEncryptorBuilder; |
|
import org.bouncycastle.openpgp.operator.bc.BcPublicKeyKeyEncryptionMethodGenerator; |
|
|
|
public class PGPHelper { |
|
|
|
public byte[] encrypt(byte[] data, PGPPublicKey pgpPublicKey) { |
|
try { |
|
PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator( |
|
new BcPGPDataEncryptorBuilder(SymmetricKeyAlgorithmTags.AES_256) |
|
.setWithIntegrityPacket(true)); |
|
encGen.addMethod(new BcPublicKeyKeyEncryptionMethodGenerator(pgpPublicKey)); |
|
ByteArrayOutputStream out = new ByteArrayOutputStream(); |
|
// create an indefinite length encrypted stream |
|
OutputStream cOut = encGen.open(out, new byte[4096]); |
|
// write out the literal data |
|
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator(); |
|
OutputStream pOut = lData.open( |
|
cOut, PGPLiteralData.BINARY, |
|
PGPLiteralData.CONSOLE, data.length, new Date()); |
|
pOut.write(data); |
|
pOut.close(); |
|
cOut.close(); |
|
return out.toByteArray(); |
|
} catch (Exception e) { |
|
throw new RuntimeException(e.getCause()); |
|
} |
|
} |
|
|
|
PGPPublicKey readPublicKey(String publicKeyFilePath) throws IOException, PGPException { |
|
val in = PGPUtil.getDecoderStream(new FileInputStream(publicKeyFilePath)); |
|
PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new BcKeyFingerprintCalculator()); |
|
PGPPublicKey key = null; |
|
Iterator rIt = pgpPub.getKeyRings(); |
|
while (key == null && rIt.hasNext()) { |
|
PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next(); |
|
Iterator kIt = kRing.getPublicKeys(); |
|
while (key == null && kIt.hasNext()) { |
|
PGPPublicKey k = (PGPPublicKey) kIt.next(); |
|
if (k.isEncryptionKey()) { |
|
key = k; |
|
} |
|
} |
|
} |
|
if (key == null) { |
|
throw new IllegalArgumentException("Can't find encryption key in key ring."); |
|
} |
|
return key; |
|
} |
|
} |
No comments:
Post a Comment