Example usage for org.bouncycastle.openpgp PGPPublicKeyRing PGPPublicKeyRing

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

Introduction

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

Prototype

public PGPPublicKeyRing(InputStream in, KeyFingerPrintCalculator fingerPrintCalculator) throws IOException 

Source Link

Usage

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

License:BEER-WARE LICENSE

/**
 * Parse a PGP public key from a string// w w w  .  j  a va 2s  .  co  m
 * @param keyString The String holding the PGP public key
 * @return PGPPublicKey
 * @throws IOException on an IO exception
 */
public static PGPPublicKey parsePublicKey(String keyString) throws IOException {
    return new PGPPublicKeyRing(new ArmoredInputStream(new ByteArrayInputStream(keyString.getBytes())),
            new BcKeyFingerprintCalculator()).getPublicKey();
}

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

License:Apache License

static final PGPPublicKeyRing readPublicKeyRing(File path) throws IOException, PGPException {
    InputStream in = null;// w  w  w . j  a v a2s.com
    try {
        in = PGPUtil.getDecoderStream(new BufferedInputStream(new FileInputStream(path)));
        return new PGPPublicKeyRing(in, new BcKeyFingerprintCalculator());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignore) {
                ; // do nothing
            }
        }
    }
}

From source file:com.google.gerrit.gpg.testutil.TestKey.java

License:Apache License

public TestKey(String pubArmored, String secArmored) {
    this.pubArmored = pubArmored;
    this.secArmored = secArmored;
    BcKeyFingerprintCalculator fc = new BcKeyFingerprintCalculator();
    try {/*from w  ww  .ja v a 2 s. c  o  m*/
        this.pubRing = new PGPPublicKeyRing(newStream(pubArmored), fc);
        this.secRing = new PGPSecretKeyRing(newStream(secArmored), fc);
    } catch (PGPException | IOException e) {
        throw new AssertionError(e);
    }
}

From source file:com.google.gerrit.server.git.gpg.TestKey.java

License:Apache License

private TestKey(String pubArmored, String secArmored) throws PGPException, IOException {
    this.pubArmored = pubArmored;
    this.secArmored = secArmored;
    BcKeyFingerprintCalculator fc = new BcKeyFingerprintCalculator();
    this.pub = new PGPPublicKeyRing(newStream(pubArmored), fc).getPublicKey();
    this.sec = new PGPSecretKeyRing(newStream(secArmored), fc).getSecretKey();
}

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

License:Apache License

/**
 * 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.//from  w ww  .  j  a  v  a  2 s .  co m
 */
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);
}

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

License:Apache License

/**
 * Fetch a secret key backup from the server and try to restore a selected secret key from it.
 *
 * @param codeCallback callback for prompting the user to provide the secret backup code.
 * @return fingerprint of the restored secret key
 *
 * @throws InterruptedException if the thread gets interrupted.
 * @throws PubSubException.NotALeafNodeException if the private node is not a {@link LeafNode}.
 * @throws XMPPException.XMPPErrorException in case of an XMPP protocol error.
 * @throws SmackException.NotConnectedException if we are not connected.
 * @throws SmackException.NoResponseException if the server doesn't respond.
 * @throws InvalidBackupCodeException if the user-provided backup code is invalid.
 * @throws SmackException.NotLoggedInException if we are not logged in
 * @throws IOException IO is dangerous//from  ww w.jav  a  2s .c om
 * @throws MissingUserIdOnKeyException if the key that is to be imported is missing a user-id with our jid
 * @throws NoBackupFoundException if no secret key backup has been found
 * @throws PGPException in case the restored secret key is damaged.
 */
public OpenPgpV4Fingerprint restoreSecretKeyServerBackup(AskForBackupCodeCallback codeCallback)
        throws InterruptedException, PubSubException.NotALeafNodeException, XMPPException.XMPPErrorException,
        SmackException.NotConnectedException, SmackException.NoResponseException, InvalidBackupCodeException,
        SmackException.NotLoggedInException, IOException, MissingUserIdOnKeyException, NoBackupFoundException,
        PGPException {
    throwIfNoProviderSet();
    throwIfNotAuthenticated();
    SecretkeyElement backup = OpenPgpPubSubUtil.fetchSecretKey(pepManager);
    if (backup == null) {
        throw new NoBackupFoundException();
    }

    String backupCode = codeCallback.askForBackupCode();

    PGPSecretKeyRing secretKeys = SecretKeyBackupHelper.restoreSecretKeyBackup(backup, backupCode);
    provider.getStore().importSecretKey(getJidOrThrow(), secretKeys);
    provider.getStore().importPublicKey(getJidOrThrow(), BCUtil.publicKeyRingFromSecretKeyRing(secretKeys));

    ByteArrayOutputStream buffer = new ByteArrayOutputStream(2048);
    for (PGPSecretKey sk : secretKeys) {
        PGPPublicKey pk = sk.getPublicKey();
        if (pk != null)
            pk.encode(buffer);
    }
    PGPPublicKeyRing publicKeys = new PGPPublicKeyRing(buffer.toByteArray(), new BcKeyFingerprintCalculator());
    provider.getStore().importPublicKey(getJidOrThrow(), publicKeys);

    return new OpenPgpV4Fingerprint(secretKeys);
}

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

License:Open Source License

public static X509Certificate createCertificate(byte[] publicKeyData, PGPSecretKey secretKey, String passphrase,
        String subjectAltName) throws PGPException, InvalidKeyException, IllegalStateException,
        NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException,
        IOException, OperatorCreationException {

    KeyFingerPrintCalculator fpr = new BcKeyFingerprintCalculator();
    PGPPublicKeyRing pubRing = new PGPPublicKeyRing(publicKeyData, fpr);

    return createCertificate(pubRing, secretKey, passphrase, subjectAltName);

}

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

License:Open Source License

public static X509Certificate createCertificate(byte[] privateKeyData, byte[] publicKeyData, String passphrase,
        String subjectAltName)/*from w ww.  j  a  va2  s  . c  om*/
        throws PGPException, IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException,
        SignatureException, CertificateException, NoSuchProviderException, OperatorCreationException {

    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(PGP.PROVIDER)
            .build(passphrase.toCharArray());

    // secret key
    PGPSecretKey secKey = secRing.getSecretKey();

    return createCertificate(pubRing, secKey.extractPrivateKey(decryptor), subjectAltName);
}

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

License:Open Source License

public static X509Certificate createCertificate(byte[] publicKeyData, PGPPrivateKey privateKey,
        String subjectAltName)/*from  w  ww  .  j  a v a  2  s.com*/
        throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException,
        CertificateException, NoSuchProviderException, PGPException, IOException, OperatorCreationException {

    KeyFingerPrintCalculator fpr = new BcKeyFingerprintCalculator();
    PGPPublicKeyRing pubRing = new PGPPublicKeyRing(publicKeyData, fpr);

    return createCertificate(pubRing, privateKey, subjectAltName);
}

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  ww w  .  jav  a  2s . 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);
}