Example usage for org.bouncycastle.openpgp PGPPublicKey getUserIDs

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

Introduction

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

Prototype

public Iterator<String> getUserIDs() 

Source Link

Document

Return any userIDs associated with the key.

Usage

From source file:alpha.offsync.security.OpenPGPSecurityUtility.java

License:Apache License

/**
 * Gets the correct encryption key from local public keyring using the
 * supplied key information.//from  w w  w .j a  v  a  2 s. c  o  m
 * 
 * @param keyInfo
 *            the supplied key information
 * @return the correct encryption key
 */
public PGPPublicKey getEncryptionKey(final String keyInfo) {
    PGPPublicKeyRingCollection pgpPub;
    try {
        pgpPub = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(new FileInputStream(this.publicKeyRing)));

        final Iterator<PGPPublicKeyRing> keyRingIter = pgpPub.getKeyRings();
        while (keyRingIter.hasNext()) {
            final PGPPublicKeyRing keyRing = keyRingIter.next();
            final Iterator keyIter = keyRing.getPublicKeys();

            while (keyIter.hasNext()) {
                final PGPPublicKey key = (PGPPublicKey) keyIter.next();

                final Iterator idIter = key.getUserIDs();
                while (idIter.hasNext()) {
                    final String userID = idIter.next().toString();
                    if (userID.contains(keyInfo) && key.isEncryptionKey())
                        return key;
                }

            }
        }

    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final PGPException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Sign the passed in message stream/*from ww  w. j av  a  2  s  .c o m*/
 */
private void signData(File inFile, OutputStream aOut, PGPPublicKey publicKey, PGPPrivateKey privateKey)
        throws PGPException {
    try {
        PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
        BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(aOut));
        PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();

        PGPSignatureGenerator sGen = new PGPSignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC");

        sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);

        @SuppressWarnings("unchecked")
        Iterator<String> users = publicKey.getUserIDs();
        if (users.hasNext()) {
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
            spGen.setSignerUserID(false, users.next());
            sGen.setHashedSubpackets(spGen.generate());
        }

        sGen.generateOnePassVersion(false).encode(bOut);

        OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, inFile);

        FileInputStream fIn = new FileInputStream(inFile);

        int ch;
        while ((ch = fIn.read()) >= 0) {
            lOut.write(ch);
            sGen.update((byte) ch);
        }

        fIn.close();

        // close() finishes the writing of the literal data and flushes the stream
        // It does not close bOut so this is ok here
        lGen.close();

        // Generate the signature
        sGen.generate().encode(bOut);

        // Must not close bOut here
        bOut.finish();
        bOut.flush();

        cGen.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in signing", e);
    }
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

public PGPSignature makeSignature(byte[] input, PGPPublicKey publicKey, PGPPrivateKey privateKey)
        throws PGPException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException {
    PGPSignatureGenerator sGen = new PGPSignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC");

    sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);

    @SuppressWarnings("unchecked")
    Iterator<String> users = publicKey.getUserIDs();
    if (users.hasNext()) {
        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, users.next());
        sGen.setHashedSubpackets(spGen.generate());
    }/*from www . ja v a2  s  .  c o m*/

    for (byte b : input) {
        sGen.update(b);
    }

    return sGen.generate();
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Find the public key for the recipient
 *///from w  ww .  jav a2s  .  co  m
public PGPPublicKey readPublicKey(PGPPublicKeyRingCollection pubRing, String recipient, boolean encrypting)
        throws IOException, PGPException {
    //
    // we just loop through the collection till we find a key suitable for encryption, in the real
    // world you would probably want to be a bit smarter about this.
    //
    PGPPublicKey key = null;

    //
    // iterate through the key rings.
    //
    @SuppressWarnings("unchecked")
    Iterator<PGPPublicKeyRing> rIt = pubRing.getKeyRings();

    //System.out.println("processing public key ring, looking for : "+recipient);
    while (key == null && rIt.hasNext()) {
        PGPPublicKeyRing kRing = rIt.next();
        //System.out.println("Found a ring with keys ");
        @SuppressWarnings("unchecked")
        Iterator<PGPPublicKey> kIt = kRing.getPublicKeys();

        //TODO bobby make sure it's safe to reuse the name from the prior key!
        String name = "<not specified>";
        while (key == null && kIt.hasNext()) {
            PGPPublicKey k = kIt.next();
            @SuppressWarnings("unchecked")
            Iterator<String> userIDs = k.getUserIDs();
            //                String name = "<not specified>";
            if (userIDs.hasNext()) {
                name = userIDs.next();
            }
            //System.out.println("found a key with name "+name);

            if (name.indexOf(recipient) >= 0) {
                if (!encrypting || k.isEncryptionKey()) {
                    //System.out.println("Found the key I'm looking for");
                    key = k;
                }
            }
        }
    }

    if (key == null) {
        if (encrypting) {
            throw new PGPException("Can't find encryption key in key ring");
        } else {
            throw new PGPException("Can't find signing key in key ring");
        }
    }

    return key;
}

From source file:com.geekcommune.identity.EncryptionUtil.java

License:Open Source License

/**
 * Find the public keys for the recipient
 *///from w w  w .jav  a 2 s. c om
public PGPPublicKeyRing findPublicKeyRing(PGPPublicKeyRingCollection pubRing, String recipient)
        throws IOException, PGPException {
    PGPPublicKeyRing retval = null;
    String retvalName = null;

    //
    // iterate through the key rings.
    //
    @SuppressWarnings("unchecked")
    Iterator<PGPPublicKeyRing> rIt = pubRing.getKeyRings();

    //System.out.println("processing public key ring, looking for : "+recipient);
    while (rIt.hasNext()) {
        PGPPublicKeyRing kRing = rIt.next();
        //System.out.println("Found a ring with keys ");
        @SuppressWarnings("unchecked")
        Iterator<PGPPublicKey> kIt = kRing.getPublicKeys();

        while (kIt.hasNext()) {
            PGPPublicKey k = kIt.next();

            String name = "<not specified>";

            @SuppressWarnings("unchecked")
            Iterator<String> userIDs = k.getUserIDs();
            if (userIDs.hasNext()) {
                name = userIDs.next();
            }
            //System.out.println("found a key with name "+name);

            if (name.indexOf(recipient) >= 0) {
                if (retval == null || retval == kRing) {
                    retval = kRing;
                    retvalName = name;
                } else {
                    throw new PGPException(
                            "Ambiguous recipient name; matches both " + name + " and " + retvalName);
                }
            }
        }
    }

    if (retval == null) {
        throw new PGPException("Can't find keyring matching " + recipient);
    }

    return retval;
}

From source file:com.github.chrbayer84.keybits.GnuPGP.java

License:Open Source License

public String showPublicKey(PGPPublicKey public_key) throws Exception {
    String ret = Long.toHexString(public_key.getKeyID()) + "\n";
    ret = ret + "   created     : " + public_key.getCreationTime() + "\n";
    ret = ret + "   valid (days): " + public_key.getValidDays() + "\n";
    ret = ret + "   users       : ";

    Iterator<String> user_iterator = public_key.getUserIDs();
    int n = 0;//from  w  w  w  . ja v  a  2 s.com
    if (user_iterator.hasNext())
        n = 2;

    while (user_iterator.hasNext())
        ret = ret + user_iterator.next() + ", ";

    ret = ret.substring(0, ret.length() - n) + "\n";

    return ret;
}

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);/*w  w w .j  ava 2 s .c  o  m*/
    }

    return key;
}

From source file:com.github.s4u.plugins.PGPVerifyMojo.java

License:Apache License

private boolean verifyPGPSignature(Artifact artifact, File artifactFile, File signatureFile)
        throws MojoFailureException {

    final Map<Integer, String> weakSignatures = ImmutableMap.<Integer, String>builder().put(1, "MD5")
            .put(4, "DOUBLE_SHA").put(5, "MD2").put(6, "TIGER_192").put(7, "HAVAL_5_160").put(11, "SHA224")
            .build();/*  w  w w.j a  v a2  s. c o m*/

    getLog().debug("Artifact file: " + artifactFile);
    getLog().debug("Artifact sign: " + signatureFile);

    try {
        InputStream sigInputStream = PGPUtil.getDecoderStream(new FileInputStream(signatureFile));
        PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(sigInputStream,
                new BcKeyFingerprintCalculator());
        PGPSignatureList sigList = (PGPSignatureList) pgpObjectFactory.nextObject();
        if (sigList == null) {
            throw new MojoFailureException("Invalid signature file: " + signatureFile);
        }
        PGPSignature pgpSignature = sigList.get(0);

        PGPPublicKey publicKey = pgpKeysCache.getKey(pgpSignature.getKeyID());

        if (!keysMap.isValidKey(artifact, publicKey)) {
            String msg = String.format("%s=0x%X", ArtifactUtils.key(artifact), publicKey.getKeyID());
            String keyUrl = pgpKeysCache.getUrlForShowKey(publicKey.getKeyID());
            getLog().error(String.format("Not allowed artifact %s and keyID:\n\t%s\n\t%s\n", artifact.getId(),
                    msg, keyUrl));
            return false;
        }

        pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);

        try (InputStream inArtifact = new BufferedInputStream(new FileInputStream(artifactFile))) {

            int t;
            while ((t = inArtifact.read()) >= 0) {
                pgpSignature.update((byte) t);
            }
        }

        String msgFormat = "%s PGP Signature %s\n       KeyId: 0x%X UserIds: %s";
        if (pgpSignature.verify()) {
            getLog().info(String.format(msgFormat, artifact.getId(), "OK", publicKey.getKeyID(),
                    Lists.newArrayList(publicKey.getUserIDs())));
            if (weakSignatures.containsKey(pgpSignature.getHashAlgorithm())) {
                if (failWeakSignature) {
                    getLog().error("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                    throw new MojoFailureException("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                } else {
                    getLog().warn("Weak signature algorithm used: "
                            + weakSignatures.get(pgpSignature.getHashAlgorithm()));
                }
            }
            return true;
        } else {
            getLog().warn(String.format(msgFormat, artifact.getId(), "ERROR", publicKey.getKeyID(),
                    Lists.newArrayList(publicKey.getUserIDs())));
            getLog().warn(artifactFile.toString());
            getLog().warn(signatureFile.toString());
            return false;
        }

    } catch (IOException | PGPException e) {
        throw new MojoFailureException(e.getMessage(), e);
    }
}

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  ww w  . j a v 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.GerritPublicKeyChecker.java

License:Apache License

@Override
public void checkCustom(PGPPublicKey key, List<String> problems) {
    try {//from w  w  w  .ja  va  2 s  . c o m
        Set<String> allowedUserIds = getAllowedUserIds();
        if (allowedUserIds.isEmpty()) {
            problems.add("No identities found for user; check " + webUrl + "#" + PageLinks.SETTINGS_WEBIDENT);
            return;
        }

        @SuppressWarnings("unchecked")
        Iterator<String> userIds = key.getUserIDs();
        while (userIds.hasNext()) {
            String userId = userIds.next();
            if (isAllowed(userId, allowedUserIds)) {
                Iterator<PGPSignature> sigs = getSignaturesForId(key, userId);
                while (sigs.hasNext()) {
                    if (isValidCertification(key, sigs.next(), userId)) {
                        return;
                    }
                }
            }
        }

        problems.add(missingUserIds(allowedUserIds));
    } catch (PGPException e) {
        String msg = "Error checking user IDs for key";
        log.warn(msg + " " + keyIdToString(key.getKeyID()), e);
        problems.add(msg);
    }
}