Example usage for org.bouncycastle.openpgp PGPPublicKey isMasterKey

List of usage examples for org.bouncycastle.openpgp PGPPublicKey isMasterKey

Introduction

In this page you can find the example usage for org.bouncycastle.openpgp PGPPublicKey isMasterKey.

Prototype

public boolean isMasterKey() 

Source Link

Document

Return true if this is a master key.

Usage

From source file:com.github.jpks.core.service.impl.PublicKeyReaderServiceImpl.java

License:Apache License

private PublicKeyImpl convert(final PGPPublicKey pgpPublicKey) {
    PublicKeyImpl key = new PublicKeyImpl();
    key.setUserIds(new ArrayList<UserIdImpl>());

    key.setKeyId(Long.toHexString(pgpPublicKey.getKeyID()).toUpperCase());
    key.setAlgo(pgpPublicKey.getAlgorithm());
    key.setKeyLen(pgpPublicKey.getBitStrength());
    key.setCreationDate(pgpPublicKey.getCreationTime());

    key.setMaster(pgpPublicKey.isMasterKey());
    key.setRevoked(pgpPublicKey.isRevoked());
    Iterator userIDs = pgpPublicKey.getUserIDs();

    while (userIDs.hasNext()) {
        String userUd = (String) userIDs.next();
        UserIdImpl userId = convert(userUd);
        userId.setCreationDate(pgpPublicKey.getCreationTime());
        key.addUserId(userId);/*from w w  w  . j  ava  2 s .com*/
    }

    return key;
}

From source file:com.google.e2e.bcdriver.KeyChecker.java

License:Apache License

/**
 * <p>This is the primary way to use this utility. It examines a
 * provided PGPPublicKeyRing and returns a wrapped object that
 * provides access only to verified key material.</p>
 *
 * @param pkr is the keyring to be examined.
 * @return an object that provides filtered access to verified key material.
 *//*from   w  ww. j  av a 2s. com*/
public static final PKR validate(PGPPublicKeyRing pkr) throws PGPException, SignatureException, IOException {

    // First handle keyring revocation/designated revokers
    PGPPublicKey masterpk = pkr.getPublicKey();
    if (!masterpk.isMasterKey()) {
        throw new IllegalArgumentException("Unexpected - first key is not master");
    }

    StringBuilder errors = new StringBuilder();

    List<UserID> userids = new ArrayList<UserID>();
    List<Subkey> subkeys = new ArrayList<Subkey>();

    int validRejects = 0;
    if (masterpk.hasRevocation()) {
        // Second pass - check for revocations.
        Iterator<PGPSignature> masterSigit = Util.getTypedIterator(
                masterpk.getSignaturesOfType(PGPSignature.KEY_REVOCATION), PGPSignature.class);
        while (masterSigit.hasNext()) {
            PGPSignature sig = masterSigit.next();
            if (isGoodDirectSignature(sig, masterpk, masterpk, errors)) {
                validRejects++;
            }
        }
    }
    if (validRejects > 0) {
        // Primary key is revoked, discard everything else.
        return new PKR(PKR.Status.REVOKED, pkr, userids, subkeys, errors);
    }

    // Filter for valid userids.
    Iterator<String> uidit = Util.getTypedIterator(masterpk.getUserIDs(), String.class);
    while (uidit.hasNext()) {
        maybeAddUserID(userids, masterpk, uidit.next(), errors);
    }

    // Don't bother with subkeys if we don't have a valid uid.
    if ((userids.size() == 0)) {
        return new PKR(PKR.Status.UNUSABLE, pkr, userids, subkeys, errors);
    }

    // Now start checking subkeys.
    Iterator<PGPPublicKey> keysit = pkr.getPublicKeys();
    // Skip the first (master) key.
    keysit.next();

    while (keysit.hasNext()) {
        PGPPublicKey subkey = keysit.next();
        if (subkey.isMasterKey()) {
            throw new IllegalArgumentException("unexpected");
        }
        maybeAddSubkey(subkeys, masterpk, subkey, errors);
    }

    return new PKR(PKR.Status.OK, pkr, userids, subkeys, errors);
}

From source file:com.google.gerrit.gpg.PublicKeyStore.java

License:Apache License

/**
 * Add a public key to the store./* w  ww .  j  a  v a 2  s.  c om*/
 * <p>
 * Multiple calls may be made to buffer keys in memory, and they are not saved
 * until {@link #save(CommitBuilder)} is called.
 *
 * @param keyRing a key ring containing exactly one public master key.
 */
public void add(PGPPublicKeyRing keyRing) {
    int numMaster = 0;
    for (PGPPublicKey key : keyRing) {
        if (key.isMasterKey()) {
            numMaster++;
        }
    }
    // We could have an additional sanity check to ensure all subkeys belong to
    // this master key, but that requires doing actual signature verification
    // here. The alternative is insane but harmless.
    if (numMaster != 1) {
        throw new IllegalArgumentException("Exactly 1 master key is required, found " + numMaster);
    }
    Fingerprint fp = new Fingerprint(keyRing.getPublicKey().getFingerprint());
    toAdd.put(fp, keyRing);
    toRemove.remove(fp);
}

From source file:de.softwareforge.pgpsigner.key.PublicKeyRing.java

License:Apache License

public void load(final String ringFileName) throws IOException, PGPException {
    File ringFile = new File(ringFileName);

    if (!ringFile.exists() || !ringFile.isFile()) {
        throw new IOException("Ring file " + ringFileName + " is not a file!");
    }/*from   w  w  w .  j  a v  a2s  .c  o  m*/

    clear();
    setRingFileName(ringFileName);

    PGPPublicKeyRingCollection publicRing = new PGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream(new FileInputStream(ringFile)));

    for (Iterator ringIt = publicRing.getKeyRings(); ringIt.hasNext();) {
        PGPPublicKeyRing keyRing = (PGPPublicKeyRing) ringIt.next();

        for (Iterator it = keyRing.getPublicKeys(); it.hasNext();) {
            PGPPublicKey publicKey = (PGPPublicKey) it.next();

            if (publicKey.isMasterKey()) {
                PublicKey pubKey = new PublicKey(publicKey);
                keys.put(pubKey.getKeyId(), pubKey);
            }
        }
    }
}

From source file:dorkbox.util.crypto.CryptoPGP.java

License:Apache License

/**
 * Find public gpg key in InputStream./*from  w  w  w .  jav  a2 s. c o m*/
 *
 * @param inputStream
 *                 the input stream
 *
 * @return the PGP public key
 */
private static PGPPublicKey findPublicGPGKey(InputStream inputStream) throws IOException, PGPException {

    // get all key rings in the input stream
    PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(
            PGPUtil.getDecoderStream(inputStream), fingerprintCalculator);

    System.err.println("key ring size: " + publicKeyRingCollection.size());

    Iterator<PGPPublicKeyRing> keyRingIter = publicKeyRingCollection.getKeyRings();

    // iterate over keyrings
    while (keyRingIter.hasNext()) {
        PGPPublicKeyRing keyRing = keyRingIter.next();
        Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys();
        // iterate over public keys in the key ring
        while (keyIter.hasNext()) {
            PGPPublicKey tmpKey = keyIter.next();

            if (tmpKey == null) {
                break;
            }

            Iterator<String> userIDs = tmpKey.getUserIDs();
            ArrayList<String> strings = new ArrayList<String>();
            while (userIDs.hasNext()) {
                String next = userIDs.next();
                strings.add(next);
            }

            System.err.println("Encryption key = " + tmpKey.isEncryptionKey() + ", Master key = "
                    + tmpKey.isMasterKey() + ", UserId = " + strings);

            // we need a master encryption key
            if (tmpKey.isEncryptionKey() && tmpKey.isMasterKey()) {
                return tmpKey;
            }
        }
    }
    throw new PGPException("No public key found!");
}

From source file:net.tjado.passwdsafe.UsbGpgBackupActivity.java

License:Open Source License

@SuppressWarnings("rawtypes")
public static PGPPublicKey readPublicKeyFromCol(InputStream in) throws IOException, PGPException {
    in = PGPUtil.getDecoderStream(in);//from  w  w w.  j a  v a 2 s . c om
    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in, new BcKeyFingerprintCalculator());
    PGPPublicKey key = null;
    Iterator rIt = pgpPub.getKeyRings();
    while (key == null && rIt.hasNext()) {
        PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
        Iterator kIt = kRing.getPublicKeys();
        while (key == null && kIt.hasNext()) {
            PGPPublicKey k = (PGPPublicKey) kIt.next();
            if (k.isEncryptionKey() && !k.isMasterKey()) {
                key = k;
            }
        }
    }
    if (key == null) {
        throw new IllegalArgumentException("Can't find encryption key in key ring.");
    }
    return key;
}

From source file:org.kontalk.certgen.PGP.java

License:Open Source License

/** Returns the first master key found in the given public keyring. */
public static PGPPublicKey getMasterKey(PGPPublicKeyRing publicKeyring) {
    @SuppressWarnings("unchecked")
    Iterator<PGPPublicKey> iter = publicKeyring.getPublicKeys();
    while (iter.hasNext()) {
        PGPPublicKey pk = iter.next();
        if (pk.isMasterKey())
            return pk;
    }/*from   w  w  w.  jav  a2 s .co  m*/

    return null;
}

From source file:org.kontalk.crypto.PersonalKey.java

License:Open Source License

/** Creates a {@link PersonalKey} from private and public key byte buffers. */
@SuppressWarnings("unchecked")
public static PersonalKey load(byte[] privateKeyData, byte[] publicKeyData, char[] passphrase,
        byte[] bridgeCertData)
        throws KonException, IOException, PGPException, CertificateException, NoSuchProviderException {
    KeyFingerPrintCalculator fpr = new BcKeyFingerprintCalculator();
    PGPSecretKeyRing secRing = new PGPSecretKeyRing(privateKeyData, fpr);
    PGPPublicKeyRing pubRing = new PGPPublicKeyRing(publicKeyData, fpr);

    PGPDigestCalculatorProvider sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build();
    PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder(sha1Calc)
            .setProvider(PGPUtils.PROVIDER).build(passphrase);

    PGPKeyPair signKp, encryptKp;//from   w w w .  j av  a2 s.  co  m

    PGPPublicKey signPub = null;
    PGPPrivateKey signPriv = null;
    PGPPublicKey encPub = null;
    PGPPrivateKey encPriv = null;

    // public keys
    Iterator<PGPPublicKey> pkeys = pubRing.getPublicKeys();
    while (pkeys.hasNext()) {
        PGPPublicKey key = pkeys.next();
        if (key.isMasterKey()) {
            // master (signing) key
            signPub = key;
        } else {
            // sub (encryption) key
            encPub = key;
        }
    }

    // secret keys
    Iterator<PGPSecretKey> skeys = secRing.getSecretKeys();
    while (skeys.hasNext()) {
        PGPSecretKey key = skeys.next();
        if (key.isMasterKey()) {
            // master (signing) key
            try {
                signPriv = key.extractPrivateKey(decryptor);
            } catch (PGPException ex) {
                throw new KonException(KonException.Error.LOAD_KEY_DECRYPT, ex);
            }
        } else {
            // sub (encryption) key
            encPriv = key.extractPrivateKey(decryptor);
        }
    }

    // X.509 bridge certificate
    X509Certificate bridgeCert = X509Bridge.load(bridgeCertData);

    if (encPriv == null || encPub == null || signPriv == null || signPub == null || bridgeCert == null)
        throw new PGPException("invalid key data");

    signKp = new PGPKeyPair(signPub, signPriv);
    encryptKp = new PGPKeyPair(encPub, encPriv);
    return new PersonalKey(signKp, encryptKp, bridgeCert);
}

From source file:org.kontalk.crypto.PGPUtils.java

License:Open Source License

/**
 * Read a public key from key ring data.
 *//*from w  w w. j  av  a  2  s .  c o  m*/
public static Optional<PGPCoderKey> readPublicKey(byte[] publicKeyring) {
    PGPPublicKeyRingCollection pgpPub;
    try {
        pgpPub = new PGPPublicKeyRingCollection(publicKeyring);
    } catch (IOException | PGPException ex) {
        LOGGER.log(Level.WARNING, "can't read public key ring", ex);
        return Optional.empty();
    }
    Iterator<?> keyRingIter = pgpPub.getKeyRings();
    if (!keyRingIter.hasNext()) {
        LOGGER.warning("no key ring in key ring collection");
        return Optional.empty();
    }
    PGPPublicKey encryptKey = null;
    String uid = null;
    String fp = null;
    PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next();
    Iterator<?> keyIter = keyRing.getPublicKeys();
    while (keyIter.hasNext()) {
        PGPPublicKey key = (PGPPublicKey) keyIter.next();
        if (key.isMasterKey()) {
            fp = EncodingUtils.bytesToHex(key.getFingerprint());
            Iterator<?> uidIt = key.getUserIDs();
            if (uidIt.hasNext())
                uid = (String) uidIt.next();
        }
        if (!key.isMasterKey() && key.isEncryptionKey()) {
            encryptKey = key;
        }
    }
    if (encryptKey == null || uid == null || fp == null) {
        LOGGER.warning("can't find public keys in key ring");
        return Optional.empty();
    }
    return Optional.of(new PGPCoderKey(encryptKey, uid, fp));
}

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  w w .  ja v a2s . c o  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;
}