Example usage for org.bouncycastle.openpgp PGPPublicKey getFingerprint

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

Introduction

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

Prototype

public byte[] getFingerprint() 

Source Link

Document

Return the fingerprint of the key.

Usage

From source file:bisq.common.crypto.PGP.java

License:Open Source License

@Nullable
public static PGPPublicKey getPubKeyFromPem(@Nullable String pem) {
    if (pem != null) {
        InputStream inputStream = new ByteArrayInputStream(pem.getBytes(Charsets.UTF_8));
        try {/*ww  w .ja  va  2 s. c  o m*/
            inputStream = PGPUtil.getDecoderStream(inputStream);
            try {
                JcaPGPPublicKeyRingCollection ringCollection = new JcaPGPPublicKeyRingCollection(inputStream);
                Iterator<PGPPublicKeyRing> keyRingsIterator = ringCollection.getKeyRings();
                while (keyRingsIterator.hasNext()) {
                    PGPPublicKeyRing pgpPublicKeyRing = keyRingsIterator.next();
                    Iterator<PGPPublicKey> pubKeysIterator = pgpPublicKeyRing.getPublicKeys();
                    while (pubKeysIterator.hasNext()) {
                        final PGPPublicKey pgpPublicKey = pubKeysIterator.next();
                        if ((pgpPublicKey).isEncryptionKey()) {
                            log.debug(pgpPublicKey.getClass().getName() + " KeyID: "
                                    + Long.toHexString(pgpPublicKey.getKeyID()) + " type: "
                                    + pgpPublicKey.getAlgorithm() + " fingerprint: "
                                    + new String(Hex.encode(pgpPublicKey.getFingerprint())));

                            BCPGKey bcKey = pgpPublicKey.getPublicKeyPacket().getKey();
                            log.debug(bcKey.getClass().getName());
                            if (bcKey instanceof RSAPublicBCPGKey) {
                                RSAPublicBCPGKey bcRSA = (RSAPublicBCPGKey) bcKey;
                                RSAPublicKeySpec specRSA = new RSAPublicKeySpec(bcRSA.getModulus(),
                                        bcRSA.getPublicExponent());
                                PublicKey jceKey = KeyFactory.getInstance("RSA").generatePublic(specRSA);
                                // if you want to use the key in JCE, use jceKey
                                // if you want to write "X.509" (SPKI) DER format to a file:
                                //Files.write(new File(pubKeyAsString).toPath(), jceKey.getEncoded());
                                // if you want to write in PEM, bouncycastle can do that
                                // or you can just do base64 and add BEGIN/END lines
                                // return pubKeyAsString; // assume only one key; if need to handle multiple keys
                                // or select other than the first, specify more clearly
                            }

                            return pgpPublicKey;
                        }
                    }
                }
                return null;
            } catch (PGPException | InvalidKeySpecException | NoSuchAlgorithmException e) {
                log.error("Error creating publicKey from pem. pem={}, error={}", pem, e);
                e.printStackTrace();
                throw new KeyConversionException(e);
            }

        } catch (IOException e) {
            log.error("Error creating publicKey from pem. pem={}, error={}", pem, e);
            e.printStackTrace();
            throw new KeyConversionException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException ignore) {
            }
        }
    } else {
        log.warn("Error creating publicKey from pem. pem=null");
        return null;
    }
}

From source file:com.geoxp.oss.MasterSecretGenerator.java

License:Apache License

public static Map<PGPPublicKey, byte[]> generate(List<PGPPublicKey> keys, int k, byte[] wrappedsecret)
        throws OSSException {

    if (null == keys) {
        throw new OSSException("Missing public PGP Public Keys.");
    }//from   w  w w . j  a v  a2s  .  c  o m

    //
    // Make sure each PGP public key can encrypt data
    //

    Set<String> nonEncryptionFingerprints = new HashSet<String>();

    for (PGPPublicKey key : keys) {
        if (!key.isEncryptionKey()) {
            nonEncryptionFingerprints.add(new String(Hex.encode(key.getFingerprint())));
        }
    }

    if (!nonEncryptionFingerprints.isEmpty()) {
        StringBuilder sb = new StringBuilder();

        sb.append("PGP Public Keys need to be encryption keys, the following keys were not:");

        for (String fpr : nonEncryptionFingerprints) {
            sb.append(" ");
            sb.append(fpr);
        }

        throw new OSSException(sb.toString());
    }

    //
    // Check value of k
    //

    if (k < 1 || k > keys.size()) {
        throw new OSSException(
                "Invalid number of needed shares, was " + k + ", should have been in [1," + keys.size() + "]");
    }

    //
    // Split the secret using Shamir Secret Sharing Scheme if k is > 1
    //

    Map<PGPPublicKey, byte[]> perkeysecret = new HashMap<PGPPublicKey, byte[]>();

    if (k == 1) {
        //
        // Simply encrypt the secret with each public key
        //

        for (PGPPublicKey key : keys) {
            try {
                perkeysecret.put(key, CryptoHelper.encryptPGP(wrappedsecret, key, true, "",
                        PGPCompressedData.ZIP, PGPEncryptedData.AES_256));
            } catch (IOException ioe) {
                throw new OSSException(ioe);
            }
        }
    } else {
        List<byte[]> secrets = CryptoHelper.SSSSSplit(wrappedsecret, keys.size(), k);

        for (int i = 0; i < keys.size(); i++) {

            PGPPublicKey key = keys.get(i);
            byte[] share = secrets.get(i);

            try {
                perkeysecret.put(key, CryptoHelper.encryptPGP(share, key, true, "", PGPCompressedData.ZIP,
                        PGPEncryptedData.AES_256));
            } catch (IOException ioe) {
                throw new OSSException(ioe);
            }
        }
    }

    return perkeysecret;
}

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

License:Apache License

public boolean isKeyMatch(PGPPublicKey pgpPublicKeyey) {

    if (matchAny) {
        return true;
    }//from w  w w  . j av a  2 s.  c om

    byte[] fingerprint = pgpPublicKeyey.getFingerprint();

    for (byte[] keyBytes : keysID) {
        if (compareArrays(keyBytes, fingerprint)) {
            return true;
        }
    }
    return false;
}

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

License:Apache License

static PGPPublicKey getPGPgpPublicKey(long keyID) {

    BigInteger bigInteger = BigInteger.valueOf(0xffff & keyID);
    BigInteger bigInteger2 = BigInteger.valueOf(keyID);

    bigInteger = bigInteger.shiftLeft(64);
    bigInteger = bigInteger.or(bigInteger2);

    bigInteger = bigInteger.shiftLeft(64);
    bigInteger = bigInteger.or(bigInteger2);

    PGPPublicKey pgpKey = mock(PGPPublicKey.class);
    when(pgpKey.getFingerprint()).thenReturn(bigInteger.toByteArray());

    return pgpKey;
}

From source file:com.goodvikings.cryptim.api.CryptimMessageListener.java

License:BEER-WARE LICENSE

private void receiveKey(String jid, String nick, Message msg) throws CryptimException {
    try {/* w  w  w.ja va2 s.  com*/
        PGPPublicKey pub = CryptimUtils.parsePublicKey(msg.getBody());

        if (confirmKey(new BigInteger(pub.getFingerprint()).toString(16))) {
            kr.addPublicKey(jid, nick, pub);
        }
    } catch (IOException e) {
        throw new CryptimException("Failed to parse Public Key", e);
    }
}

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

License:Apache License

private CheckResult checkWebOfTrust(PGPPublicKey key, PublicKeyStore store, int depth, Set<Fingerprint> seen) {
    if (trusted == null || store == null) {
        return CheckResult.OK; // Trust checking not configured.
    }/*from   w  w  w  . jav  a2s  .  c  om*/
    Fingerprint fp = new Fingerprint(key.getFingerprint());
    if (seen.contains(fp)) {
        return new CheckResult("Key is trusted in a cycle");
    }
    seen.add(fp);

    Fingerprint trustedFp = trusted.get(key.getKeyID());
    if (trustedFp != null && trustedFp.equals(fp)) {
        return CheckResult.OK; // Directly trusted.
    } else if (depth >= maxTrustDepth) {
        return new CheckResult("No path of depth <= " + maxTrustDepth + " to a trusted key");
    }

    List<CheckResult> signerResults = new ArrayList<>();
    @SuppressWarnings("unchecked")
    Iterator<String> userIds = key.getUserIDs();
    while (userIds.hasNext()) {
        String userId = userIds.next();
        @SuppressWarnings("unchecked")
        Iterator<PGPSignature> sigs = key.getSignaturesForID(userId);
        while (sigs.hasNext()) {
            PGPSignature sig = sigs.next();
            // TODO(dborowitz): Handle CERTIFICATION_REVOCATION.
            if (sig.getSignatureType() != PGPSignature.DEFAULT_CERTIFICATION
                    && sig.getSignatureType() != PGPSignature.POSITIVE_CERTIFICATION) {
                continue; // Not a certification.
            }

            PGPPublicKey signer = getSigner(store, sig, userId, key, signerResults);
            // TODO(dborowitz): Require self certification.
            if (signer == null || Arrays.equals(signer.getFingerprint(), key.getFingerprint())) {
                continue;
            }
            CheckResult signerResult = checkTrustSubpacket(sig, depth);
            if (signerResult.isOk()) {
                signerResult = check(signer, store, depth + 1, false, seen);
                if (signerResult.isOk()) {
                    return CheckResult.OK;
                }
            }
            signerResults.add(new CheckResult(
                    "Certification by " + keyToString(signer) + " is valid, but key is not trusted"));
        }
    }

    List<String> problems = new ArrayList<>();
    problems.add("No path to a trusted key");
    for (CheckResult signerResult : signerResults) {
        problems.addAll(signerResult.getProblems());
    }
    return new CheckResult(problems);
}

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

License:Apache License

public static String keyToString(PGPPublicKey key) {
    @SuppressWarnings("unchecked")
    Iterator<String> it = key.getUserIDs();
    return String.format("%s %s(%s)", keyIdToString(key.getKeyID()), it.hasNext() ? it.next() + " " : "",
            Fingerprint.toString(key.getFingerprint()));
}

From source file:com.google.gerrit.gpg.server.DeleteGpgKey.java

License:Apache License

@Override
public Response<?> apply(GpgKey rsrc, Input input)
        throws ResourceConflictException, PGPException, OrmException, IOException {
    PGPPublicKey key = rsrc.getKeyRing().getPublicKey();
    AccountExternalId.Key extIdKey = new AccountExternalId.Key(AccountExternalId.SCHEME_GPGKEY,
            BaseEncoding.base16().encode(key.getFingerprint()));
    db.get().accountExternalIds().deleteKeys(Collections.singleton(extIdKey));

    try (PublicKeyStore store = storeProvider.get()) {
        store.remove(rsrc.getKeyRing().getPublicKey().getFingerprint());

        CommitBuilder cb = new CommitBuilder();
        PersonIdent committer = serverIdent.get();
        cb.setAuthor(rsrc.getUser().newCommitterIdent(committer.getWhen(), committer.getTimeZone()));
        cb.setCommitter(committer);//from www .  j a v  a2  s  .c  om
        cb.setMessage("Delete public key " + keyIdToString(key.getKeyID()));

        RefUpdate.Result saveResult = store.save(cb);
        switch (saveResult) {
        case NO_CHANGE:
        case FAST_FORWARD:
            break;
        default:
            throw new ResourceConflictException("Failed to delete public key: " + saveResult);
        }
    }
    return Response.none();
}

From source file:com.google.gerrit.gpg.server.GpgKeys.java

License:Apache License

@Override
public GpgKey parse(AccountResource parent, IdString id)
        throws ResourceNotFoundException, PGPException, OrmException, IOException {
    checkEnabled();//from   w  w  w.j av  a  2s.  co m
    String str = CharMatcher.WHITESPACE.removeFrom(id.get()).toUpperCase();
    if ((str.length() != 8 && str.length() != 40) || !CharMatcher.anyOf("0123456789ABCDEF").matchesAllOf(str)) {
        throw new ResourceNotFoundException(id);
    }

    byte[] fp = parseFingerprint(id.get(), getGpgExtIds(parent));
    try (PublicKeyStore store = storeProvider.get()) {
        long keyId = keyId(fp);
        for (PGPPublicKeyRing keyRing : store.get(keyId)) {
            PGPPublicKey key = keyRing.getPublicKey();
            if (Arrays.equals(key.getFingerprint(), fp)) {
                return new GpgKey(parent.getUser(), keyRing);
            }
        }
    }

    throw new ResourceNotFoundException(id);
}

From source file:com.google.gerrit.gpg.server.GpgKeys.java

License:Apache License

static GpgKeyInfo toJson(PGPPublicKeyRing keyRing) throws IOException {
    PGPPublicKey key = keyRing.getPublicKey();
    GpgKeyInfo info = new GpgKeyInfo();
    info.id = PublicKeyStore.keyIdToString(key.getKeyID());
    info.fingerprint = Fingerprint.toString(key.getFingerprint());
    @SuppressWarnings("unchecked")
    Iterator<String> userIds = key.getUserIDs();
    info.userIds = ImmutableList.copyOf(userIds);
    try (ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
            ArmoredOutputStream aout = new ArmoredOutputStream(out)) {
        // This is not exactly the key stored in the store, but is equivalent. In
        // particular, it will have a Bouncy Castle version string. The armored
        // stream reader in PublicKeyStore doesn't give us an easy way to extract
        // the original ASCII armor.
        key.encode(aout);//w  w w .  j  ava2 s. com
        info.key = new String(out.toByteArray(), UTF_8);
    }
    return info;
}