use of org.bouncycastle.openpgp.PGPException in project nifi by apache.
the class OpenPGPKeyBasedEncryptor method getPublicKey.
/*
* Get the public key for a specific user id from a keyring.
*/
@SuppressWarnings("rawtypes")
public static PGPPublicKey getPublicKey(String userId, String publicKeyringFile) throws IOException, PGPException {
// Read in from the public keyring file
try (FileInputStream keyInputStream = new FileInputStream(publicKeyringFile)) {
// Form the PublicKeyRing collection (1.53 way with fingerprint calculator)
PGPPublicKeyRingCollection pgpPublicKeyRingCollection = new PGPPublicKeyRingCollection(keyInputStream, new BcKeyFingerprintCalculator());
// Iterate over all public keyrings
Iterator<PGPPublicKeyRing> iter = pgpPublicKeyRingCollection.getKeyRings();
PGPPublicKeyRing keyRing;
while (iter.hasNext()) {
keyRing = iter.next();
// Iterate over each public key in this keyring
Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
while (keyIter.hasNext()) {
PGPPublicKey publicKey = keyIter.next();
// Iterate over each userId attached to the public key
Iterator userIdIterator = publicKey.getUserIDs();
while (userIdIterator.hasNext()) {
String id = (String) userIdIterator.next();
if (userId.equalsIgnoreCase(id)) {
return publicKey;
}
}
}
}
}
// If this point is reached, no public key could be extracted with the given userId
throw new PGPException("Could not find a public key with the given userId");
}
use of org.bouncycastle.openpgp.PGPException in project incubator-gobblin by apache.
the class GPGFileDecryptor method decryptFile.
/**
* Taking in a file inputstream, keyring inputstream and a passPhrase, generate a decrypted file inputstream.
* @param inputStream file inputstream
* @param keyIn keyring inputstream
* @param passPhrase passPhrase
* @return
* @throws IOException
*/
@SneakyThrows(PGPException.class)
public InputStream decryptFile(InputStream inputStream, InputStream keyIn, String passPhrase) throws IOException {
PGPEncryptedDataList enc = getPGPEncryptedDataList(inputStream);
Iterator it = enc.getEncryptedDataObjects();
PGPPrivateKey sKey = null;
PGPPublicKeyEncryptedData pbe = null;
PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn), new BcKeyFingerprintCalculator());
while (sKey == null && it.hasNext()) {
pbe = (PGPPublicKeyEncryptedData) it.next();
sKey = findSecretKey(pgpSec, pbe.getKeyID(), passPhrase);
}
if (sKey == null) {
throw new IllegalArgumentException("secret key for message not found.");
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(sKey))) {
JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);
Object pgpfObject = pgpFact.nextObject();
while (pgpfObject != null) {
if (pgpfObject instanceof PGPCompressedData) {
PGPCompressedData cData = (PGPCompressedData) pgpfObject;
pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
pgpfObject = pgpFact.nextObject();
}
if (pgpfObject instanceof PGPLiteralData) {
Streams.pipeAll(((PGPLiteralData) pgpfObject).getInputStream(), outputStream);
} else if (pgpfObject instanceof PGPOnePassSignatureList) {
throw new PGPException("encrypted message contains PGPOnePassSignatureList message - not literal data.");
} else if (pgpfObject instanceof PGPSignatureList) {
throw new PGPException("encrypted message contains PGPSignatureList message - not literal data.");
} else {
throw new PGPException("message is not a simple encrypted file - type unknown.");
}
pgpfObject = pgpFact.nextObject();
}
return new ByteArrayInputStream(outputStream.toByteArray());
} finally {
outputStream.close();
}
}
use of org.bouncycastle.openpgp.PGPException in project iaf by ibissource.
the class PGPAction method configure.
/**
* Generates a keyring configuration with public keys and the private key.
*
* @throws ConfigurationException When the files do not exist, or unexpected PGP exception has occurred.
*/
public void configure() throws ConfigurationException {
try {
// Create configuration
KeyringConfigCallback callback = KeyringConfigCallbacks.withUnprotectedKeys();
if (secretPassword != null)
callback = KeyringConfigCallbacks.withPassword(secretPassword);
keyringConfig = KeyringConfigs.forGpgExportedKeys(callback);
// Add public keys
if (publicKeys != null) {
for (String s : publicKeys) {
URL url = ClassUtils.getResourceURL(this, s);
keyringConfig.addPublicKey(IOUtils.toByteArray(url.openStream()));
}
}
// Add private key
if (secretKey != null) {
URL url = ClassUtils.getResourceURL(this, secretKey);
keyringConfig.addSecretKey(IOUtils.toByteArray(url.openStream()));
}
} catch (IOException | PGPException e) {
throw new ConfigurationException("Unknown exception has occurred.", e);
}
}
use of org.bouncycastle.openpgp.PGPException in project keywhiz by square.
the class BackupResource method backup.
/**
* Backup all secrets for a given group. Returns an encrypted encrypted to
* the backup key in the main configuration file. Only accessible to automation clients.
*
* @param name Group name
*
* @return Encrypted archive
*/
@Timed
@ExceptionMetered
@GET
@Path("{key}/group/{group}")
@Produces(APPLICATION_OCTET_STREAM)
public byte[] backup(@Auth AutomationClient automationClient, @PathParam("group") String name, @PathParam("key") String key) {
if (config.getBackupExportKey(key) == null) {
throw new NotFoundException("Unknown key: " + key);
}
Optional<Group> groupOptional = groupDAO.getGroup(name);
if (!groupOptional.isPresent()) {
throw new NotFoundException("Unknown group: " + name);
}
Group group = groupOptional.get();
// SecretDeliveryResponse is the same data a client receives when requesting a secret,
// so it should have all the relevant information we need (including content, checksum).
List<SecretDeliveryResponse> secrets = secretController.getSecretsForGroup(group).stream().map(SecretDeliveryResponse::fromSecret).collect(toList());
String serialized;
try {
serialized = objectMapper.writeValueAsString(secrets);
} catch (JsonProcessingException e) {
// This should never happen
logger.error("Unable to backup secrets", e);
throw new InternalServerErrorException("Unable to backup secrets, check logs for details");
}
// Record all checksums of backed up/exported secrets so we can uniquely identify which
// particular contents were returned in the response from inspection of the audit log.
Map<String, String> auditInfo = secrets.stream().collect(toMap(SecretDeliveryResponse::getName, SecretDeliveryResponse::getChecksum));
// Record audit event
auditLog.recordEvent(new Event(now(), GROUP_BACKUP, automationClient.getName(), group.getName(), auditInfo));
// Perform encryption & return encrypted data
try {
Key exportKey = new Key(config.getBackupExportKey(key));
Encryptor encryptor = new Encryptor(exportKey);
encryptor.setEncryptionAlgorithm(AES256);
encryptor.setSigningAlgorithm(Unsigned);
encryptor.setCompressionAlgorithm(ZIP);
ByteArrayInputStream plaintext = new ByteArrayInputStream(serialized.getBytes(UTF_8));
ByteArrayOutputStream ciphertext = new ByteArrayOutputStream();
encryptor.encrypt(plaintext, ciphertext, new FileMetadata(format("%s.json", group), UTF8));
return ciphertext.toByteArray();
} catch (PGPException | IOException e) {
logger.error("Unable to backup secrets", e);
throw new InternalServerErrorException("Unable to backup secrets, check logs for details");
}
}
use of org.bouncycastle.openpgp.PGPException in project keywhiz by square.
the class ExpirationExtractor method expirationFromOpenPGP.
@Nullable
public static Instant expirationFromOpenPGP(byte[] content) {
JcaPGPPublicKeyRingCollection collection;
try {
collection = new JcaPGPPublicKeyRingCollection(new ByteArrayInputStream(content));
} catch (IOException | PGPException e) {
// Unable to parse
logger.info("Failed to parse OpenPGP keyring", e);
return null;
}
Instant earliest = null;
// Iterate over all key rings in file
Iterator rings = collection.getKeyRings();
while (rings.hasNext()) {
Object ringItem = rings.next();
if (ringItem instanceof PGPPublicKeyRing) {
PGPPublicKeyRing ring = (PGPPublicKeyRing) ringItem;
// Iterate over all keys in ring
Iterator keys = ring.getPublicKeys();
while (keys.hasNext()) {
Object keyItem = keys.next();
if (keyItem instanceof PGPPublicKey) {
PGPPublicKey key = (PGPPublicKey) keyItem;
// Get validity for key (zero means no expiry)
long validSeconds = key.getValidSeconds();
if (validSeconds > 0) {
Instant expiry = key.getCreationTime().toInstant().plusSeconds(validSeconds);
if (earliest == null || expiry.isBefore(earliest)) {
earliest = expiry;
}
}
}
}
}
}
return earliest;
}
Aggregations