Search in sources :

Example 6 with PGPException

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");
}
Also used : PGPException(org.bouncycastle.openpgp.PGPException) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) PGPPublicKeyRingCollection(org.bouncycastle.openpgp.PGPPublicKeyRingCollection) Iterator(java.util.Iterator) BcKeyFingerprintCalculator(org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) FileInputStream(java.io.FileInputStream)

Example 7 with PGPException

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();
    }
}
Also used : PGPOnePassSignatureList(org.bouncycastle.openpgp.PGPOnePassSignatureList) PGPLiteralData(org.bouncycastle.openpgp.PGPLiteralData) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) JcePublicKeyDataDecryptorFactoryBuilder(org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyDataDecryptorFactoryBuilder) PGPEncryptedDataList(org.bouncycastle.openpgp.PGPEncryptedDataList) PGPSignatureList(org.bouncycastle.openpgp.PGPSignatureList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) PGPCompressedData(org.bouncycastle.openpgp.PGPCompressedData) PGPException(org.bouncycastle.openpgp.PGPException) ByteArrayInputStream(java.io.ByteArrayInputStream) Iterator(java.util.Iterator) PGPSecretKeyRingCollection(org.bouncycastle.openpgp.PGPSecretKeyRingCollection) BcKeyFingerprintCalculator(org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator) PGPPublicKeyEncryptedData(org.bouncycastle.openpgp.PGPPublicKeyEncryptedData) PGPPrivateKey(org.bouncycastle.openpgp.PGPPrivateKey) JcaPGPObjectFactory(org.bouncycastle.openpgp.jcajce.JcaPGPObjectFactory) SneakyThrows(lombok.SneakyThrows)

Example 8 with PGPException

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);
    }
}
Also used : PGPException(org.bouncycastle.openpgp.PGPException) KeyringConfigCallback(name.neuhalfen.projects.crypto.bouncycastle.openpgp.keys.callbacks.KeyringConfigCallback) ConfigurationException(nl.nn.adapterframework.configuration.ConfigurationException) IOException(java.io.IOException) URL(java.net.URL)

Example 9 with PGPException

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");
    }
}
Also used : Group(keywhiz.api.model.Group) FileMetadata(org.c02e.jpgpj.FileMetadata) NotFoundException(javax.ws.rs.NotFoundException) Encryptor(org.c02e.jpgpj.Encryptor) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SecretDeliveryResponse(keywhiz.api.SecretDeliveryResponse) PGPException(org.bouncycastle.openpgp.PGPException) ByteArrayInputStream(java.io.ByteArrayInputStream) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Event(keywhiz.log.Event) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Key(org.c02e.jpgpj.Key) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) Timed(com.codahale.metrics.annotation.Timed) GET(javax.ws.rs.GET) ExceptionMetered(com.codahale.metrics.annotation.ExceptionMetered)

Example 10 with PGPException

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;
}
Also used : PGPException(org.bouncycastle.openpgp.PGPException) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) ByteArrayInputStream(java.io.ByteArrayInputStream) Instant(java.time.Instant) Iterator(java.util.Iterator) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) PemObject(org.bouncycastle.util.io.pem.PemObject) IOException(java.io.IOException) JcaPGPPublicKeyRingCollection(org.bouncycastle.openpgp.jcajce.JcaPGPPublicKeyRingCollection) Nullable(javax.annotation.Nullable)

Aggregations

PGPException (org.bouncycastle.openpgp.PGPException)22 IOException (java.io.IOException)14 InputStream (java.io.InputStream)7 BcKeyFingerprintCalculator (org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator)7 PGPPublicKey (org.bouncycastle.openpgp.PGPPublicKey)6 PGPPublicKeyRing (org.bouncycastle.openpgp.PGPPublicKeyRing)6 FileInputStream (java.io.FileInputStream)4 ArrayList (java.util.ArrayList)4 PGPPublicKeyRingCollection (org.bouncycastle.openpgp.PGPPublicKeyRingCollection)4 PGPSignature (org.bouncycastle.openpgp.PGPSignature)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 HashMap (java.util.HashMap)3 Iterator (java.util.Iterator)3 PGPEncryptedDataList (org.bouncycastle.openpgp.PGPEncryptedDataList)3 PGPObjectFactory (org.bouncycastle.openpgp.PGPObjectFactory)3 PGPPrivateKey (org.bouncycastle.openpgp.PGPPrivateKey)3 PGPPublicKeyEncryptedData (org.bouncycastle.openpgp.PGPPublicKeyEncryptedData)3 PGPSecretKeyRingCollection (org.bouncycastle.openpgp.PGPSecretKeyRingCollection)3 PublicKeyStore.keyIdToString (com.google.gerrit.gpg.PublicKeyStore.keyIdToString)2