Search in sources :

Example 11 with PGPException

use of org.bouncycastle.openpgp.PGPException in project Smack by igniterealtime.

the class OpenPgpContact method updateKeys.

/**
 * Update the contacts keys using a prefetched {@link PublicKeysListElement}.
 *
 * @param connection our {@link XMPPConnection}.
 * @param metadata pre-fetched OX metadata node of the contact.
 *
 * @throws InterruptedException in case the thread gets interrupted.
 * @throws SmackException.NotConnectedException in case the connection is not connected.
 * @throws SmackException.NoResponseException in case the server doesn't respond.
 * @throws IOException IO is dangerous.
 */
public void updateKeys(XMPPConnection connection, PublicKeysListElement metadata) throws InterruptedException, SmackException.NotConnectedException, SmackException.NoResponseException, IOException {
    Map<OpenPgpV4Fingerprint, Date> fingerprintsAndDates = new HashMap<>();
    for (OpenPgpV4Fingerprint fingerprint : metadata.getMetadata().keySet()) {
        fingerprintsAndDates.put(fingerprint, metadata.getMetadata().get(fingerprint).getDate());
    }
    store.setAnnouncedFingerprintsOf(getJid(), fingerprintsAndDates);
    Map<OpenPgpV4Fingerprint, Date> fetchDates = store.getPublicKeyFetchDates(getJid());
    for (OpenPgpV4Fingerprint fingerprint : metadata.getMetadata().keySet()) {
        Date fetchDate = fetchDates.get(fingerprint);
        if (fetchDate != null && fingerprintsAndDates.get(fingerprint) != null && fetchDate.after(fingerprintsAndDates.get(fingerprint))) {
            LOGGER.log(Level.FINE, "Skip key " + Long.toHexString(fingerprint.getKeyId()) + " as we already have the most recent version. " + "Last announced: " + fingerprintsAndDates.get(fingerprint).toString() + " Last fetched: " + fetchDate.toString());
            continue;
        }
        try {
            PubkeyElement key = OpenPgpPubSubUtil.fetchPubkey(connection, getJid(), fingerprint);
            unfetchableKeys.remove(fingerprint);
            fetchDates.put(fingerprint, new Date());
            if (key == null) {
                LOGGER.log(Level.WARNING, "Public key " + Long.toHexString(fingerprint.getKeyId()) + " can not be imported: Is null");
                unfetchableKeys.put(fingerprint, new NullPointerException("Public key is null."));
                continue;
            }
            PGPPublicKeyRing keyRing = new PGPPublicKeyRing(Base64.decode(key.getDataElement().getB64Data()), new BcKeyFingerprintCalculator());
            store.importPublicKey(getJid(), keyRing);
        } catch (PubSubException.NotAPubSubNodeException | PubSubException.NotALeafNodeException | XMPPException.XMPPErrorException e) {
            LOGGER.log(Level.WARNING, "Error fetching public key " + Long.toHexString(fingerprint.getKeyId()), e);
            unfetchableKeys.put(fingerprint, e);
        } catch (PGPException | IOException e) {
            LOGGER.log(Level.WARNING, "Public key " + Long.toHexString(fingerprint.getKeyId()) + " can not be imported.", e);
            unfetchableKeys.put(fingerprint, e);
        } catch (MissingUserIdOnKeyException e) {
            LOGGER.log(Level.WARNING, "Public key " + Long.toHexString(fingerprint.getKeyId()) + " is missing the user-id \"xmpp:" + getJid() + "\". Refuse to import it.", e);
            unfetchableKeys.put(fingerprint, e);
        }
    }
    store.setPublicKeyFetchDates(getJid(), fetchDates);
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) HashMap(java.util.HashMap) IOException(java.io.IOException) Date(java.util.Date) PGPException(org.bouncycastle.openpgp.PGPException) PubkeyElement(org.jivesoftware.smackx.ox.element.PubkeyElement) BcKeyFingerprintCalculator(org.bouncycastle.openpgp.operator.bc.BcKeyFingerprintCalculator) OpenPgpV4Fingerprint(org.pgpainless.key.OpenPgpV4Fingerprint) MissingUserIdOnKeyException(org.jivesoftware.smackx.ox.exception.MissingUserIdOnKeyException)

Example 12 with PGPException

use of org.bouncycastle.openpgp.PGPException in project Smack by igniterealtime.

the class PainlessOpenPgpProvider method decryptAndOrVerify.

@Override
public OpenPgpMessage decryptAndOrVerify(XMPPConnection connection, OpenPgpElement element, final OpenPgpSelf self, final OpenPgpContact sender) throws IOException, PGPException {
    ByteArrayOutputStream plainText = new ByteArrayOutputStream();
    InputStream cipherText = element.toInputStream();
    PGPPublicKeyRingCollection announcedPublicKeys = sender.getAnnouncedPublicKeys();
    if (announcedPublicKeys == null) {
        try {
            sender.updateKeys(connection);
            announcedPublicKeys = sender.getAnnouncedPublicKeys();
        } catch (InterruptedException | NotALeafNodeException | NotAPubSubNodeException | NotConnectedException | NoResponseException | XMPPErrorException e) {
            throw new PGPException("Abort decryption due to lack of keys", e);
        }
    }
    MissingPublicKeyCallback missingPublicKeyCallback = new MissingPublicKeyCallback() {

        @Override
        public PGPPublicKeyRing onMissingPublicKeyEncountered(Long keyId) {
            try {
                sender.updateKeys(connection);
                PGPPublicKeyRingCollection anyKeys = sender.getAnyPublicKeys();
                for (PGPPublicKeyRing ring : anyKeys) {
                    if (ring.getPublicKey(keyId) != null) {
                        return ring;
                    }
                }
                return null;
            } catch (InterruptedException | NotALeafNodeException | NotAPubSubNodeException | NotConnectedException | NoResponseException | XMPPErrorException | IOException | PGPException e) {
                LOGGER.log(Level.WARNING, "Cannot fetch missing key " + keyId, e);
                return null;
            }
        }
    };
    DecryptionStream cipherStream = PGPainless.decryptAndOrVerify().onInputStream(cipherText).withOptions(new ConsumerOptions().addDecryptionKeys(self.getSecretKeys(), getStore().getKeyRingProtector()).addVerificationCerts(announcedPublicKeys).setMissingCertificateCallback(missingPublicKeyCallback));
    Streams.pipeAll(cipherStream, plainText);
    cipherText.close();
    cipherStream.close();
    plainText.close();
    OpenPgpMetadata info = cipherStream.getResult();
    OpenPgpMessage.State state;
    if (info.isSigned()) {
        if (info.isEncrypted()) {
            state = OpenPgpMessage.State.signcrypt;
        } else {
            state = OpenPgpMessage.State.sign;
        }
    } else if (info.isEncrypted()) {
        state = OpenPgpMessage.State.crypt;
    } else {
        throw new PGPException("Received message appears to be neither encrypted, nor signed.");
    }
    return new OpenPgpMessage(plainText.toByteArray(), state, info);
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) NotALeafNodeException(org.jivesoftware.smackx.pubsub.PubSubException.NotALeafNodeException) NotConnectedException(org.jivesoftware.smack.SmackException.NotConnectedException) InputStream(java.io.InputStream) ConsumerOptions(org.pgpainless.decryption_verification.ConsumerOptions) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DecryptionStream(org.pgpainless.decryption_verification.DecryptionStream) PGPException(org.bouncycastle.openpgp.PGPException) PGPPublicKeyRingCollection(org.bouncycastle.openpgp.PGPPublicKeyRingCollection) NotAPubSubNodeException(org.jivesoftware.smackx.pubsub.PubSubException.NotAPubSubNodeException) OpenPgpMessage(org.jivesoftware.smackx.ox.OpenPgpMessage) NoResponseException(org.jivesoftware.smack.SmackException.NoResponseException) MissingPublicKeyCallback(org.pgpainless.decryption_verification.MissingPublicKeyCallback) OpenPgpMetadata(org.pgpainless.decryption_verification.OpenPgpMetadata)

Example 13 with PGPException

use of org.bouncycastle.openpgp.PGPException in project gradle by gradle.

the class PgpSignatory method sign.

/**
 * Exhausts {@code toSign}, and writes the signature to {@code signatureDestination}.
 *
 * The caller is responsible for closing the streams, though the output WILL be flushed.
 */
@Override
public void sign(InputStream toSign, OutputStream signatureDestination) {
    PGPSignatureGenerator generator = createSignatureGenerator();
    try {
        feedGeneratorWith(toSign, generator);
        PGPSignature signature = generator.generate();
        writeSignatureTo(signatureDestination, signature);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } catch (PGPException e) {
        throw UncheckedException.throwAsUncheckedException(e);
    }
}
Also used : PGPSignatureGenerator(org.bouncycastle.openpgp.PGPSignatureGenerator) PGPException(org.bouncycastle.openpgp.PGPException) UncheckedIOException(org.gradle.api.UncheckedIOException) PGPSignature(org.bouncycastle.openpgp.PGPSignature) IOException(java.io.IOException) UncheckedIOException(org.gradle.api.UncheckedIOException)

Example 14 with PGPException

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

the class PostGpgKeys method apply.

@Override
public Map<String, GpgKeyInfo> apply(AccountResource rsrc, Input input) throws ResourceNotFoundException, BadRequestException, ResourceConflictException, PGPException, OrmException, IOException, ConfigInvalidException {
    GpgKeys.checkVisible(self, rsrc);
    Collection<ExternalId> existingExtIds = externalIds.byAccount(rsrc.getUser().getAccountId(), SCHEME_GPGKEY);
    try (PublicKeyStore store = storeProvider.get()) {
        Set<Fingerprint> toRemove = readKeysToRemove(input, existingExtIds);
        List<PGPPublicKeyRing> newKeys = readKeysToAdd(input, toRemove);
        List<ExternalId> newExtIds = new ArrayList<>(existingExtIds.size());
        for (PGPPublicKeyRing keyRing : newKeys) {
            PGPPublicKey key = keyRing.getPublicKey();
            ExternalId.Key extIdKey = toExtIdKey(key.getFingerprint());
            Account account = getAccountByExternalId(extIdKey);
            if (account != null) {
                if (!account.getId().equals(rsrc.getUser().getAccountId())) {
                    throw new ResourceConflictException("GPG key already associated with another account");
                }
            } else {
                newExtIds.add(ExternalId.create(extIdKey, rsrc.getUser().getAccountId()));
            }
        }
        storeKeys(rsrc, newKeys, toRemove);
        List<ExternalId.Key> extIdKeysToRemove = toRemove.stream().map(fp -> toExtIdKey(fp.get())).collect(toList());
        externalIdsUpdateFactory.create().replace(rsrc.getUser().getAccountId(), extIdKeysToRemove, newExtIds);
        accountCache.evict(rsrc.getUser().getAccountId());
        return toJson(newKeys, toRemove, store, rsrc.getUser());
    }
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) OrmException(com.google.gwtorm.server.OrmException) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) Inject(com.google.inject.Inject) LoggerFactory(org.slf4j.LoggerFactory) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) ByteArrayInputStream(java.io.ByteArrayInputStream) GpgKeyInfo(com.google.gerrit.extensions.common.GpgKeyInfo) Map(java.util.Map) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) PGPException(org.bouncycastle.openpgp.PGPException) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) Set(java.util.Set) RefUpdate(org.eclipse.jgit.lib.RefUpdate) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) SCHEME_GPGKEY(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_GPGKEY) Sets(com.google.common.collect.Sets) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) Joiner(com.google.common.base.Joiner) Singleton(com.google.inject.Singleton) AccountCache(com.google.gerrit.server.account.AccountCache) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) InternalAccountQuery(com.google.gerrit.server.query.account.InternalAccountQuery) GerritPublicKeyChecker(com.google.gerrit.gpg.GerritPublicKeyChecker) Fingerprint(com.google.gerrit.gpg.Fingerprint) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) Account(com.google.gerrit.reviewdb.client.Account) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ArmoredInputStream(org.bouncycastle.bcpg.ArmoredInputStream) CheckResult(com.google.gerrit.gpg.CheckResult) Input(com.google.gerrit.gpg.server.PostGpgKeys.Input) CurrentUser(com.google.gerrit.server.CurrentUser) Logger(org.slf4j.Logger) BaseEncoding(com.google.common.io.BaseEncoding) UTF_8(java.nio.charset.StandardCharsets.UTF_8) AccountResource(com.google.gerrit.server.account.AccountResource) EmailException(com.google.gerrit.common.errors.EmailException) PublicKeyChecker(com.google.gerrit.gpg.PublicKeyChecker) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) AddKeySender(com.google.gerrit.server.mail.send.AddKeySender) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AccountState(com.google.gerrit.server.account.AccountState) BcPGPObjectFactory(org.bouncycastle.openpgp.bc.BcPGPObjectFactory) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) InputStream(java.io.InputStream) PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) Account(com.google.gerrit.reviewdb.client.Account) Fingerprint(com.google.gerrit.gpg.Fingerprint) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey)

Example 15 with PGPException

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

the class PublicKeyChecker method gatherRevocationProblems.

private void gatherRevocationProblems(PGPPublicKey key, Date now, List<String> problems) {
    try {
        List<PGPSignature> revocations = new ArrayList<>();
        Map<Long, RevocationKey> revokers = new HashMap<>();
        PGPSignature selfRevocation = scanRevocations(key, now, revocations, revokers);
        if (selfRevocation != null) {
            RevocationReason reason = getRevocationReason(selfRevocation);
            if (isRevocationValid(selfRevocation, reason, now)) {
                problems.add(reasonToString(reason));
            }
        } else {
            checkRevocations(key, revocations, revokers, problems);
        }
    } catch (PGPException | IOException e) {
        problems.add("Error checking key revocation");
    }
}
Also used : RevocationReason(org.bouncycastle.bcpg.sig.RevocationReason) PGPException(org.bouncycastle.openpgp.PGPException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) RevocationKey(org.bouncycastle.bcpg.sig.RevocationKey) PGPSignature(org.bouncycastle.openpgp.PGPSignature) IOException(java.io.IOException)

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