Search in sources :

Example 1 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project camel by apache.

the class PGPKeyAccessDataFormat method getSignature.

protected PGPOnePassSignature getSignature(Exchange exchange, PGPOnePassSignatureList signatureList) throws Exception {
    if (SIGNATURE_VERIFICATION_OPTION_IGNORE.equals(getSignatureVerificationOption())) {
        return null;
    }
    if (SIGNATURE_VERIFICATION_OPTION_NO_SIGNATURE_ALLOWED.equals(getSignatureVerificationOption())) {
        throw new PGPException("PGP message contains a signature although a signature is not expected. Either change the configuration of the PGP decryptor or send a PGP message with no signature.");
    }
    List<String> allowedUserIds = determineSignaturenUserIds(exchange);
    for (int i = 0; i < signatureList.size(); i++) {
        PGPOnePassSignature signature = signatureList.get(i);
        // Determine public key from signature keyId
        PGPPublicKey sigPublicKey = publicKeyAccessor.getPublicKey(exchange, signature.getKeyID(), allowedUserIds);
        if (sigPublicKey == null) {
            continue;
        }
        // choose that signature for which a public key exists!
        signature.init(new JcaPGPContentVerifierBuilderProvider().setProvider(getProvider()), sigPublicKey);
        return signature;
    }
    if (signatureList.isEmpty()) {
        return null;
    } else {
        throw new IllegalArgumentException("Cannot verify the PGP signature: No public key found for the key ID(s) contained in the PGP signature(s). " + "Either the received PGP message contains a signature from an unexpected sender or the Public Keyring does not contain the public key of the sender.");
    }
}
Also used : PGPException(org.bouncycastle.openpgp.PGPException) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) PGPOnePassSignature(org.bouncycastle.openpgp.PGPOnePassSignature) JcaPGPContentVerifierBuilderProvider(org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentVerifierBuilderProvider)

Example 2 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project camel by apache.

the class PGPKeyAccessDataFormat method marshal.

public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
    //NOPMD
    List<String> userids = determineEncryptionUserIds(exchange);
    List<PGPPublicKey> keys = publicKeyAccessor.getEncryptionKeys(exchange, userids);
    if (keys.isEmpty()) {
        throw new IllegalArgumentException("Cannot PGP encrypt message. No public encryption key found for the User Ids " + userids + " in the public keyring. Either specify other User IDs or add correct public keys to the keyring.");
    }
    exchange.getOut().setHeader(NUMBER_OF_ENCRYPTION_KEYS, Integer.valueOf(keys.size()));
    InputStream input = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
    if (armored) {
        outputStream = new ArmoredOutputStream(outputStream);
    }
    PGPEncryptedDataGenerator encGen = new PGPEncryptedDataGenerator(new JcePGPDataEncryptorBuilder(findAlgorithm(exchange)).setWithIntegrityPacket(integrity).setSecureRandom(new SecureRandom()).setProvider(getProvider()));
    // several keys can be added
    for (PGPPublicKey key : keys) {
        encGen.addMethod(new JcePublicKeyKeyEncryptionMethodGenerator(key));
    }
    OutputStream encOut = encGen.open(outputStream, new byte[BUFFER_SIZE]);
    OutputStream comOut;
    if (withCompressedDataPacket) {
        PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(findCompressionAlgorithm(exchange));
        comOut = new BufferedOutputStream(comData.open(encOut));
    } else {
        comOut = encOut;
        LOG.debug("No Compressed Data packet is added");
    }
    List<PGPSignatureGenerator> sigGens = createSignatureGenerator(exchange, comOut);
    PGPLiteralDataGenerator litData = new PGPLiteralDataGenerator();
    String fileName = findFileName(exchange);
    OutputStream litOut = litData.open(comOut, PGPLiteralData.BINARY, fileName, new Date(), new byte[BUFFER_SIZE]);
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            litOut.write(buffer, 0, bytesRead);
            if (sigGens != null && !sigGens.isEmpty()) {
                for (PGPSignatureGenerator sigGen : sigGens) {
                    // not nested therefore it is the same for all
                    // can this be improved that we only do it for one sigGen and set the result on the others?
                    sigGen.update(buffer, 0, bytesRead);
                }
            }
            litOut.flush();
        }
    } finally {
        IOHelper.close(litOut);
        if (sigGens != null && !sigGens.isEmpty()) {
            // reverse order
            for (int i = sigGens.size() - 1; i > -1; i--) {
                PGPSignatureGenerator sigGen = sigGens.get(i);
                sigGen.generate().encode(comOut);
            }
        }
        IOHelper.close(comOut, encOut, outputStream, input);
    }
}
Also used : PGPSignatureGenerator(org.bouncycastle.openpgp.PGPSignatureGenerator) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) PGPCompressedDataGenerator(org.bouncycastle.openpgp.PGPCompressedDataGenerator) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) ArmoredOutputStream(org.bouncycastle.bcpg.ArmoredOutputStream) SecureRandom(java.security.SecureRandom) PGPLiteralDataGenerator(org.bouncycastle.openpgp.PGPLiteralDataGenerator) PGPEncryptedDataGenerator(org.bouncycastle.openpgp.PGPEncryptedDataGenerator) Date(java.util.Date) JcePublicKeyKeyEncryptionMethodGenerator(org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator) BufferedOutputStream(java.io.BufferedOutputStream) JcePGPDataEncryptorBuilder(org.bouncycastle.openpgp.operator.jcajce.JcePGPDataEncryptorBuilder)

Example 3 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project camel by apache.

the class PGPDataFormatUtil method findPublicKeys.

public static List<PGPPublicKey> findPublicKeys(List<String> useridParts, boolean forEncryption, PGPPublicKeyRingCollection pgpPublicKeyringCollection) {
    List<PGPPublicKey> result = new ArrayList<PGPPublicKey>(useridParts.size());
    for (Iterator<PGPPublicKeyRing> keyRingIter = pgpPublicKeyringCollection.getKeyRings(); keyRingIter.hasNext(); ) {
        PGPPublicKeyRing keyRing = keyRingIter.next();
        PGPPublicKey primaryKey = keyRing.getPublicKey();
        String[] foundKeyUserIdForUserIdPart = findFirstKeyUserIdContainingOneOfTheParts(useridParts, primaryKey);
        if (foundKeyUserIdForUserIdPart == null) {
            LOG.debug("No User ID found in primary key with key ID {} containing one of the parts {}", primaryKey.getKeyID(), useridParts);
            continue;
        }
        LOG.debug("User ID {} found in primary key with key ID {} containing one of the parts {}", new Object[] { foundKeyUserIdForUserIdPart[0], primaryKey.getKeyID(), useridParts });
        // add adequate keys to the result
        for (Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); keyIter.hasNext(); ) {
            PGPPublicKey key = keyIter.next();
            if (forEncryption) {
                if (isEncryptionKey(key)) {
                    LOG.debug("Public encryption key with key user ID {} and key ID {} added to the encryption keys", foundKeyUserIdForUserIdPart[0], Long.toString(key.getKeyID()));
                    result.add(key);
                }
            } else if (!forEncryption && isSignatureKey(key)) {
                // not used!
                result.add(key);
                LOG.debug("Public key with key user ID {} and key ID {} added to the signing keys", foundKeyUserIdForUserIdPart[0], Long.toString(key.getKeyID()));
            }
        }
    }
    return result;
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) ArrayList(java.util.ArrayList) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey)

Example 4 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey 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)

Example 5 with PGPPublicKey

use of org.bouncycastle.openpgp.PGPPublicKey in project gerrit by GerritCodeReview.

the class GpgKeys method parse.

@Override
public GpgKey parse(AccountResource parent, IdString id) throws ResourceNotFoundException, PGPException, OrmException, IOException {
    checkVisible(self, parent);
    String str = CharMatcher.whitespace().removeFrom(id.get()).toUpperCase();
    if ((str.length() != 8 && str.length() != 40) || !CharMatcher.anyOf("0123456789ABCDEF").matchesAllOf(str)) {
        throw new ResourceNotFoundException(id);
    }
    byte[] fp = parseFingerprint(id.get(), getGpgExtIds(parent));
    try (PublicKeyStore store = storeProvider.get()) {
        long keyId = keyId(fp);
        for (PGPPublicKeyRing keyRing : store.get(keyId)) {
            PGPPublicKey key = keyRing.getPublicKey();
            if (Arrays.equals(key.getFingerprint(), fp)) {
                return new GpgKey(parent.getUser(), keyRing);
            }
        }
    }
    throw new ResourceNotFoundException(id);
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) IdString(com.google.gerrit.extensions.restapi.IdString) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Aggregations

PGPPublicKey (org.bouncycastle.openpgp.PGPPublicKey)26 PGPPublicKeyRing (org.bouncycastle.openpgp.PGPPublicKeyRing)12 PublicKeyStore.keyToString (com.google.gerrit.gpg.PublicKeyStore.keyToString)8 PublicKeyStore.keyIdToString (com.google.gerrit.gpg.PublicKeyStore.keyIdToString)6 Test (org.junit.Test)6 ArrayList (java.util.ArrayList)5 PublicKeyStore (com.google.gerrit.gpg.PublicKeyStore)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 PGPException (org.bouncycastle.openpgp.PGPException)4 GpgKeyInfo (com.google.gerrit.extensions.common.GpgKeyInfo)3 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)3 CheckResult (com.google.gerrit.gpg.CheckResult)3 Fingerprint (com.google.gerrit.gpg.Fingerprint)3 TestKey (com.google.gerrit.gpg.testutil.TestKey)3 GerritPersonIdent (com.google.gerrit.server.GerritPersonIdent)3 IOException (java.io.IOException)3 PGPPublicKeyRingCollection (org.bouncycastle.openpgp.PGPPublicKeyRingCollection)3 BcPGPContentVerifierBuilderProvider (org.bouncycastle.openpgp.operator.bc.BcPGPContentVerifierBuilderProvider)3 CommitBuilder (org.eclipse.jgit.lib.CommitBuilder)3