Example usage for org.bouncycastle.openpgp PGPPublicKeyRing getPublicKey

List of usage examples for org.bouncycastle.openpgp PGPPublicKeyRing getPublicKey

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPPublicKeyRing getPublicKey.

Prototype

public PGPPublicKey getPublicKey(byte[] fingerprint) 

Source Link

Document

Return the public key with the passed in fingerprint if it is present.

Usage

From source file:bisq.desktop.main.overlays.windows.downloadupdate.BisqInstaller.java

License:Open Source License

/**
 * Verifies detached PGP signatures against GPG/openPGP RSA public keys. Does currently not work with openssl or JCA/JCE keys.
 *
 * @param pubKeyFile Path to file providing the public key to use
 * @param sigFile    Path to detached signature file
 * @param dataFile   Path to signed data file
 * @return {@code true} if signature is valid, {@code false} if signature is not valid
 * @throws Exception throws various exceptions in case something went wrong. Main reason should be that key or
 *                   signature could be extracted from the provided files due to a "bad" format.<br>
 *                   <code>FileNotFoundException, IOException, SignatureException, PGPException</code>
 *///w ww.j  av  a  2 s  .c  om
public static VerifyStatusEnum verifySignature(File pubKeyFile, File sigFile, File dataFile) throws Exception {
    InputStream inputStream;
    int bytesRead;
    PGPPublicKey publicKey;
    PGPSignature pgpSignature;
    boolean result;

    // Read keys from file
    inputStream = PGPUtil.getDecoderStream(new FileInputStream(pubKeyFile));
    PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(inputStream,
            new JcaKeyFingerprintCalculator());
    inputStream.close();

    Iterator<PGPPublicKeyRing> iterator = publicKeyRingCollection.getKeyRings();
    PGPPublicKeyRing pgpPublicKeyRing;
    if (iterator.hasNext()) {
        pgpPublicKeyRing = iterator.next();
    } else {
        throw new PGPException("Could not find public keyring in provided key file");
    }

    // Would be the solution for multiple keys in one file
    //        Iterator<PGPPublicKey> kIt;
    //        kIt = pgpPublicKeyRing.getPublicKeys();
    //        publicKey = pgpPublicKeyRing.getPublicKey(0xF5B84436F379A1C6L);

    // Read signature from file
    inputStream = PGPUtil.getDecoderStream(new FileInputStream(sigFile));
    PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(inputStream, new JcaKeyFingerprintCalculator());
    Object o = pgpObjectFactory.nextObject();
    if (o instanceof PGPSignatureList) {
        PGPSignatureList signatureList = (PGPSignatureList) o;
        checkArgument(!signatureList.isEmpty(), "signatureList must not be empty");
        pgpSignature = signatureList.get(0);
    } else if (o instanceof PGPSignature) {
        pgpSignature = (PGPSignature) o;
    } else {
        throw new SignatureException("Could not find signature in provided signature file");
    }
    inputStream.close();
    log.debug("KeyID used in signature: %X\n", pgpSignature.getKeyID());
    publicKey = pgpPublicKeyRing.getPublicKey(pgpSignature.getKeyID());

    // If signature is not matching the key used for signing we fail
    if (publicKey == null)
        return VerifyStatusEnum.FAIL;

    log.debug("The ID of the selected key is %X\n", publicKey.getKeyID());
    pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);

    // Read file to verify
    byte[] data = new byte[1024];
    inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile)));
    while (true) {
        bytesRead = inputStream.read(data, 0, 1024);
        if (bytesRead == -1)
            break;
        pgpSignature.update(data, 0, bytesRead);
    }
    inputStream.close();

    // Verify the signature
    result = pgpSignature.verify();
    return result ? VerifyStatusEnum.OK : VerifyStatusEnum.FAIL;
}

From source file:org.jivesoftware.smackx.ox.OpenPgpContact.java

License:Apache License

/**
 * Return any announced public keys. This is the set returned by {@link #getAnyPublicKeys()} with non-announced
 * keys and keys which lack a user-id with the contacts jid removed.
 *
 * @return announced keys of the contact
 *
 * @throws IOException IO is dangerous/* w ww. j av a 2 s .com*/
 * @throws PGPException PGP is brittle
 */
public PGPPublicKeyRingCollection getAnnouncedPublicKeys() throws IOException, PGPException {
    PGPPublicKeyRingCollection anyKeys = getAnyPublicKeys();
    Map<OpenPgpV4Fingerprint, Date> announced = store.getAnnouncedFingerprintsOf(jid);

    BareJidUserId.PubRingSelectionStrategy userIdFilter = new BareJidUserId.PubRingSelectionStrategy();

    PGPPublicKeyRingCollection announcedKeysCollection = null;
    for (OpenPgpV4Fingerprint announcedFingerprint : announced.keySet()) {
        PGPPublicKeyRing ring = anyKeys.getPublicKeyRing(announcedFingerprint.getKeyId());

        if (ring == null)
            continue;

        ring = BCUtil.removeUnassociatedKeysFromKeyRing(ring,
                ring.getPublicKey(announcedFingerprint.getKeyId()));

        if (!userIdFilter.accept(getJid(), ring)) {
            LOGGER.log(Level.WARNING, "Ignore key " + Long.toHexString(ring.getPublicKey().getKeyID())
                    + " as it lacks the user-id \"xmpp" + getJid().toString() + "\"");
            continue;
        }

        if (announcedKeysCollection == null) {
            announcedKeysCollection = new PGPPublicKeyRingCollection(Collections.singleton(ring));
        } else {
            announcedKeysCollection = PGPPublicKeyRingCollection.addPublicKeyRing(announcedKeysCollection,
                    ring);
        }
    }

    return announcedKeysCollection;
}

From source file:org.kontalk.xmppserver.pgp.PGPUtils.java

License:Open Source License

public static PGPPublicKeyRing merge(PGPPublicKeyRing oldRing, PGPPublicKeyRing newRing)
        throws PGPException, IOException {
    if (!equals(oldRing, newRing)) {
        throw new PGPKeyValidationException("keys are not equal");
    }//  w ww.  j  a v a2  s . co m

    // remember which certs we already added. this is cheaper than semantic deduplication
    Set<byte[]> certs = new TreeSet<>(new Comparator<byte[]>() {
        public int compare(byte[] left, byte[] right) {
            // check for length equality
            if (left.length != right.length) {
                return left.length - right.length;
            }
            // compare byte-by-byte
            for (int i = 0; i < left.length; i++) {
                if (left[i] != right[i]) {
                    return (left[i] & 0xff) - (right[i] & 0xff);
                }
            }
            // ok they're the same
            return 0;
        }
    });

    PGPPublicKeyRing result = oldRing;
    PGPPublicKeyRing candidate = newRing;

    // Pre-load all existing certificates
    for (@SuppressWarnings("unchecked")
    Iterator<PGPPublicKey> i = result.getPublicKeys(); i.hasNext();) {
        PGPPublicKey key = i.next();
        for (@SuppressWarnings("unchecked")
        Iterator<PGPSignature> j = key.getSignatures(); j.hasNext();) {
            PGPSignature cert = j.next();
            certs.add(cert.getEncoded());
        }
    }

    for (@SuppressWarnings("unchecked")
    Iterator<PGPPublicKey> i = candidate.getPublicKeys(); i.hasNext();) {
        PGPPublicKey key = i.next();

        final PGPPublicKey resultKey = result.getPublicKey(key.getKeyID());
        if (resultKey == null) {
            // otherwise, just insert the public key
            result = PGPPublicKeyRing.insertPublicKey(result, key);
            continue;
        }

        // Modifiable version of the old key, which we merge stuff into (keep old for comparison)
        PGPPublicKey modified = resultKey;

        // Iterate certifications
        for (@SuppressWarnings("unchecked")
        Iterator<PGPSignature> j = key.getSignatures(); j.hasNext();) {
            PGPSignature cert = j.next();
            byte[] encoded = cert.getEncoded();
            // Known cert, skip it
            if (certs.contains(encoded)) {
                continue;
            }
            certs.add(encoded);
            modified = PGPPublicKey.addCertification(modified, cert);
        }

        // If this is a subkey, merge it in and stop here
        if (!key.isMasterKey()) {
            if (modified != resultKey) {
                result = PGPPublicKeyRing.insertPublicKey(result, modified);
            }
            continue;
        }

        // Copy over all user id certificates
        for (@SuppressWarnings("unchecked")
        Iterator<byte[]> r = key.getRawUserIDs(); r.hasNext();) {
            byte[] rawUserId = r.next();

            @SuppressWarnings("unchecked")
            Iterator<PGPSignature> signaturesIt = key.getSignaturesForID(rawUserId);
            // no signatures for this User ID, skip it
            if (signaturesIt == null) {
                continue;
            }
            while (signaturesIt.hasNext()) {
                PGPSignature cert = signaturesIt.next();
                byte[] encoded = cert.getEncoded();
                // Known cert, skip it
                if (certs.contains(encoded)) {
                    continue;
                }
                certs.add(encoded);
                modified = PGPPublicKey.addCertification(modified, rawUserId, cert);
            }
        }

        // Copy over all user attribute certificates
        for (@SuppressWarnings("unchecked")
        Iterator<PGPUserAttributeSubpacketVector> v = key.getUserAttributes(); v.hasNext();) {
            PGPUserAttributeSubpacketVector vector = v.next();

            @SuppressWarnings("unchecked")
            Iterator<PGPSignature> signaturesIt = key.getSignaturesForUserAttribute(vector);
            // no signatures for this user attribute attribute, skip it
            if (signaturesIt == null) {
                continue;
            }
            while (signaturesIt.hasNext()) {
                PGPSignature cert = signaturesIt.next();
                byte[] encoded = cert.getEncoded();
                // Known cert, skip it
                if (certs.contains(encoded)) {
                    continue;
                }
                certs.add(encoded);
                modified = PGPPublicKey.addCertification(modified, vector, cert);
            }
        }

        // If anything change, save the updated (sub)key
        if (modified != resultKey) {
            result = PGPPublicKeyRing.insertPublicKey(result, modified);
        }

    }

    return result;
}

From source file:uk.co.platosys.dinigma.Lock.java

License:GNU General Public License

/**
 *Certifies a PGP public key within this Lock.
 *
 * @param keyID the keyID of the public key to be certified
 * @param key the key of the person doing the certifying
 * @param passphrase the corresponding passphrase
 * @throws MinigmaException//  w w w. ja  va2  s  .  c  om
 */
public void certify(long keyID, Key key, char[] passphrase) throws MinigmaException {
    try {
        if (publicKeys.contains(keyID)) {
            try {
                PGPPublicKeyRing pkr = publicKeys.getPublicKeyRing(keyID);
                PGPPublicKey publicKey = pkr.getPublicKey(keyID);
                PGPSignature signature = SignatureEngine.getKeyCertification(key, passphrase, publicKey);
                PGPPublicKey.addCertification(publicKey, signature);
            } catch (Exception x) {
                throw new MinigmaException("Problem certifying key", x);
            }
        } else {
            throw new MinigmaException("key " + Kidney.toString(keyID) + " not in this lock");
        }
    } catch (Exception x) {
        throw new MinigmaException("certification issues", x);

    }

}