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);
}
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);
}
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);
}
}
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());
}
}
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");
}
}
Aggregations