Example usage for org.bouncycastle.openpgp PGPSecretKeyRingCollection PGPSecretKeyRingCollection

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

Introduction

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

Prototype

public PGPSecretKeyRingCollection(InputStream in, KeyFingerPrintCalculator fingerPrintCalculator)
        throws IOException, PGPException 

Source Link

Document

Build a PGPSecretKeyRingCollection from the passed in input stream.

Usage

From source file:com.arcusx.simplepgp.PgpDataDecryptor.java

public void decrypt(InputStream encryptedIn, InputStream privateKeyIn, InputStream publicKeyIn,
        OutputStream plainOut, boolean signatureRequired) throws PGPException, IOException {
    encryptedIn = PGPUtil.getDecoderStream(encryptedIn);

    try {/*from  www. ja va  2s.  co m*/
        JcaPGPObjectFactory pgpObjectFactory = new JcaPGPObjectFactory(encryptedIn);

        Object o = pgpObjectFactory.nextObject();

        //
        // the first object might be a PGP marker packet.
        //
        PGPEncryptedDataList enc;
        if (o instanceof PGPEncryptedDataList) {
            enc = (PGPEncryptedDataList) o;
        } else {
            enc = (PGPEncryptedDataList) pgpObjectFactory.nextObject();
        }

        //
        // find the secret key
        //
        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey privateKey = null;
        PGPPublicKeyEncryptedData publicKeyEncryptedData = null;
        PGPSecretKeyRingCollection privateKeyRingCollection = new PGPSecretKeyRingCollection(
                PGPUtil.getDecoderStream(privateKeyIn), new JcaKeyFingerprintCalculator());

        while (privateKey == null && it.hasNext()) {
            publicKeyEncryptedData = (PGPPublicKeyEncryptedData) it.next();
            privateKey = findSecretKey(privateKeyRingCollection, publicKeyEncryptedData.getKeyID(),
                    "".toCharArray());
        }

        if (privateKey == null) {
            throw new IllegalArgumentException("Secret key for message not found.");
        }

        PublicKeyDataDecryptorFactory decryptorFactory = new JcePublicKeyDataDecryptorFactoryBuilder()
                .setProvider("BC").build(privateKey);
        InputStream clearTextIn = publicKeyEncryptedData.getDataStream(decryptorFactory);

        PGPOnePassSignature onePassSignature = null;
        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clearTextIn);

        Object message = pgpFact.nextObject();
        if (message instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) message;
            pgpFact = new JcaPGPObjectFactory(cData.getDataStream());

            message = pgpFact.nextObject();
        }

        if (message instanceof PGPOnePassSignatureList) {
            PGPOnePassSignatureList onePassSignatureList = (PGPOnePassSignatureList) message;
            onePassSignature = onePassSignatureList.get(0);
            message = pgpFact.nextObject();
        }

        if (onePassSignature == null && signatureRequired) {
            throw new SecurityException("No signature object found.");
        }

        if (message instanceof PGPLiteralData) {
            PGPLiteralData literalData = (PGPLiteralData) message;
            InputStream literalDataIn = literalData.getInputStream();

            PGPPublicKey publicKey = PgpKeyUtils.readPublicKey(publicKeyIn);
            if (onePassSignature != null) {
                onePassSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey);
            }

            int len = 0;
            byte[] buf = new byte[BUFFER_SIZE];
            while ((len = literalDataIn.read(buf, 0, buf.length)) >= 0) {
                if (onePassSignature != null) {
                    onePassSignature.update(buf, 0, len);
                }

                plainOut.write(buf, 0, len);
            }

            if (onePassSignature != null) {
                PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
                PGPSignature signature = p3.get(0);
                if (!onePassSignature.verify(signature))
                    throw new PGPException("Signature invalid.");
            }

            plainOut.close();
        } else {
            throw new PGPException("message is not a simple encrypted file - type unknown." + message);
        }

        if (!publicKeyEncryptedData.isIntegrityProtected())
            throw new IllegalStateException("Message is not integrity protected.");

        if (!publicKeyEncryptedData.verify())
            throw new IllegalStateException("Message is integrity protected but integrity check failed.");
    } catch (NoSuchProviderException ex) {
        throw new PGPException("Decryption failed.", ex);
    } finally {
        IOUtils.closeQuietly(encryptedIn);
        IOUtils.closeQuietly(privateKeyIn);
        IOUtils.closeQuietly(publicKeyIn);
        IOUtils.closeQuietly(plainOut);
    }
}

From source file:com.arcusx.simplepgp.PgpKeyUtils.java

public static PGPSecretKey findSecretKey(InputStream privateKeyIn) throws PGPException, IOException {

    //TODO FIXME//from   w  w w.  j  a v a  2s  . c  o  m
    InputStream in = PGPUtil.getDecoderStream(privateKeyIn);
    KeyFingerPrintCalculator fingerPrintCalculator = null;

    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(in, fingerPrintCalculator);

    for (Iterator<PGPSecretKeyRing> iter = pgpSec.getKeyRings(); iter.hasNext();) {
        PGPSecretKeyRing pgpSecretKeyRing = iter.next();
        for (Iterator<PGPSecretKey> keysIter = pgpSecretKeyRing.getSecretKeys(); keysIter.hasNext();) {
            PGPSecretKey secretKey = keysIter.next();
            return secretKey;
        }
    }

    throw new NoSuchElementException("No private key found.");
}

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

License:Apache License

/**
 * Find private gpg key in InputStream, also closes the input stream
 *
 * @param inputStream/*from   w ww  .j  a  v a  2s .  co  m*/
 *                 the inputStream that contains the private (secret) key
 * @param userId
 *                 the user id
 *
 * @return the PGP secret key
 */
public static List<PGPSecretKey> getSecretKeys(InputStream inputStream, String userId) throws PGPException {
    // iterate over every private key in the key ring
    PGPSecretKeyRingCollection secretKeyRings;
    try {
        secretKeyRings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(inputStream),
                fingerprintCalculator);
    } catch (IOException e) {
        throw new PGPException("No private key found in stream!", e);
    } finally {
        IO.close(inputStream);
    }

    // look for the key ring that is used to authenticate our reporting facilities
    Iterator<PGPSecretKeyRing> secretKeys = secretKeyRings.getKeyRings(userId);
    List<PGPSecretKey> pgpSecretKeys = new ArrayList<PGPSecretKey>();

    // iterate over every private key in the ring
    while (secretKeys.hasNext()) {
        PGPSecretKeyRing secretKeyRing = secretKeys.next();
        PGPSecretKey tmpKey = secretKeyRing.getSecretKey();

        if (tmpKey != null) {
            pgpSecretKeys.add(tmpKey);
        }
    }

    if (!pgpSecretKeys.isEmpty()) {
        return pgpSecretKeys;
    }

    throw new PGPException("No private key found in stream!");
}

From source file:hh.learnj.test.license.test.lincense3j.KeyBasedFileProcessor.java

/**
 * decrypt the passed in message stream//from   w  w  w.  j  a  v a  2s . c  om
 */
private static void decryptFile(InputStream in, InputStream keyIn, char[] passwd, String defaultFileName)
        throws IOException, NoSuchProviderException {
    in = PGPUtil.getDecoderStream(in);
    try {
        JcaPGPObjectFactory pgpF = new JcaPGPObjectFactory(in);
        PGPEncryptedDataList enc;

        Object o = pgpF.nextObject();
        //
        // the first object might be a PGP marker packet.
        //
        if (o instanceof PGPEncryptedDataList) {
            enc = (PGPEncryptedDataList) o;
        } else {
            enc = (PGPEncryptedDataList) pgpF.nextObject();
        }
        //
        // find the secret key
        //
        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey sKey = null;
        PGPPublicKeyEncryptedData pbe = null;
        PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
                new JcaKeyFingerprintCalculator());

        while (sKey == null && it.hasNext()) {
            pbe = (PGPPublicKeyEncryptedData) it.next();
            sKey = MyPGPUtil.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
        }
        if (sKey == null) {
            throw new IllegalArgumentException("secret key for message not found.");
        }
        InputStream clear = pbe
                .getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder().setProvider("BC").build(sKey));
        JcaPGPObjectFactory plainFact = new JcaPGPObjectFactory(clear);
        Object message = plainFact.nextObject();
        if (message instanceof PGPCompressedData) {
            PGPCompressedData cData = (PGPCompressedData) message;
            JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(cData.getDataStream());
            message = pgpFact.nextObject();
        }
        if (message instanceof PGPLiteralData) {
            PGPLiteralData ld = (PGPLiteralData) message;

            String outFileName = ld.getFileName();
            if (outFileName.length() == 0) {
                outFileName = defaultFileName;
            } else {
                /**
                 * modify 20160520 set fileName ????????
                 */
                String separator = "";
                if (outFileName.contains("/")) {
                    separator = "/";
                } else if (outFileName.contains("\\")) {
                    separator = "\\";

                }
                String fileName = outFileName.substring(outFileName.lastIndexOf(separator) + 1);
                //
                String defseparator = "";
                if (defaultFileName.contains("/")) {
                    defseparator = "/";
                } else if (defaultFileName.contains("\\")) {
                    defseparator = "\\";
                }

                defaultFileName = defaultFileName.substring(0, defaultFileName.lastIndexOf(defseparator));

                outFileName = defaultFileName + File.separator + fileName;

            }

            InputStream unc = ld.getInputStream();
            OutputStream fOut = new BufferedOutputStream(new FileOutputStream(outFileName));

            Streams.pipeAll(unc, fOut);

            fOut.close();
        } else if (message instanceof PGPOnePassSignatureList) {
            throw new PGPException("encrypted message contains a signed message - not literal data.");
        } else {
            throw new PGPException("message is not a simple encrypted file - type unknown.");
        }

        if (pbe.isIntegrityProtected()) {
            if (!pbe.verify()) {
                System.err.println("message failed integrity check");
            } else {
                System.err.println("message integrity check passed");
            }
        } else {
            System.err.println("no message integrity check");
        }
    } catch (PGPException e) {
        System.err.println(e);
        if (e.getUnderlyingException() != null) {
            e.getUnderlyingException().printStackTrace();
        }
    }
}

From source file:hh.learnj.test.license.test.lincense3j.MyPGPUtil.java

/**
 * A simple routine that opens a key ring file and loads the first available
 * key suitable for signature generation.
 *
 * @param input/*from   w w  w  .  jav  a 2s .  c o m*/
 *            stream to read the secret key ring collection from.
 * @return a secret key.
 * @throws IOException
 *             on a problem with using the input stream.
 * @throws PGPException
 *             if there is an issue parsing the input stream.
 */
public static PGPSecretKey readSecretKey(InputStream input) throws IOException, PGPException {
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input),
            new JcaKeyFingerprintCalculator());

    //
    // 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.
    //

    Iterator keyRingIter = pgpSec.getKeyRings();
    while (keyRingIter.hasNext()) {
        PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRingIter.next();

        Iterator keyIter = keyRing.getSecretKeys();
        while (keyIter.hasNext()) {
            PGPSecretKey key = (PGPSecretKey) keyIter.next();

            if (key.isSigningKey()) {
                return key;
            }
        }
    }
    throw new IllegalArgumentException("Can't find signing key in key ring.");
}

From source file:net.staticsnow.nexus.repository.apt.internal.gpg.AptSigningFacet.java

License:Open Source License

private PGPSecretKey readSecretKey() throws IOException, PGPException {
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
            PGPUtil.getDecoderStream(new ByteArrayInputStream(config.keypair.getBytes())),
            new JcaKeyFingerprintCalculator());

    Iterator<PGPSecretKeyRing> keyRings = pgpSec.getKeyRings();
    while (keyRings.hasNext()) {
        PGPSecretKeyRing keyRing = (PGPSecretKeyRing) keyRings.next();

        Iterator<PGPSecretKey> keys = keyRing.getSecretKeys();
        while (keys.hasNext()) {
            PGPSecretKey key = (PGPSecretKey) keys.next();

            if (key.isSigningKey()) {
                return key;
            }// w  w  w  .  j a v  a 2 s.  c o  m
        }
    }

    throw new IllegalStateException("Can't find signing key in key ring.");
}

From source file:org.apache.gobblin.crypto.GPGFileDecryptor.java

License:Apache License

/**
 * Taking in a file inputstream, keyring inputstream and a passPhrase, generate a decrypted file inputstream.
 * @param inputStream file inputstream//from w  ww . j  ava 2 s .c om
 * @param keyIn keyring inputstream. This InputStream is owned by the caller.
 * @param passPhrase passPhrase
 * @return an {@link InputStream} for the decrypted content
 * @throws IOException
 */
public InputStream decryptFile(InputStream inputStream, InputStream keyIn, String passPhrase)
        throws IOException {
    try {
        PGPEncryptedDataList enc = getPGPEncryptedDataList(inputStream);
        Iterator it = enc.getEncryptedDataObjects();
        PGPPrivateKey sKey = null;
        PGPPublicKeyEncryptedData pbe = null;
        PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn),
                new BcKeyFingerprintCalculator());

        while (sKey == null && it.hasNext()) {
            pbe = (PGPPublicKeyEncryptedData) it.next();
            sKey = findSecretKey(pgpSec, pbe.getKeyID(), passPhrase);
        }

        if (sKey == null) {
            throw new IllegalArgumentException("secret key for message not found.");
        }

        InputStream clear = pbe.getDataStream(new JcePublicKeyDataDecryptorFactoryBuilder()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(sKey));
        JcaPGPObjectFactory pgpFact = new JcaPGPObjectFactory(clear);

        return new LazyMaterializeDecryptorInputStream(pgpFact);
    } catch (PGPException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.nifi.processors.standard.util.crypto.OpenPGPKeyBasedEncryptor.java

License:Apache License

private static PGPPrivateKey getDecryptedPrivateKey(String provider, String secretKeyringFile, long keyId,
        char[] passphrase) throws IOException, PGPException {
    // TODO: Reevaluate the mechanism for executing this task as performance can suffer here and only a specific key needs to be validated

    // Read in from the secret keyring file
    try (FileInputStream keyInputStream = new FileInputStream(secretKeyringFile)) {

        // Form the SecretKeyRing collection (1.53 way with fingerprint calculator)
        PGPSecretKeyRingCollection pgpSecretKeyRingCollection = new PGPSecretKeyRingCollection(keyInputStream,
                new BcKeyFingerprintCalculator());

        // The decryptor is identical for all keys
        final PBESecretKeyDecryptor decryptor = new JcePBESecretKeyDecryptorBuilder().setProvider(provider)
                .build(passphrase);//from   w ww .  ja  va 2s .  c om

        // Iterate over all secret keyrings
        Iterator<PGPSecretKeyRing> keyringIterator = pgpSecretKeyRingCollection.getKeyRings();
        PGPSecretKeyRing keyRing;
        PGPSecretKey secretKey;

        while (keyringIterator.hasNext()) {
            keyRing = keyringIterator.next();

            // If keyId exists, get a specific secret key; else, iterate over all
            if (keyId != 0) {
                secretKey = keyRing.getSecretKey(keyId);
                try {
                    return secretKey.extractPrivateKey(decryptor);
                } catch (Exception e) {
                    throw new PGPException("No private key available using passphrase", e);
                }
            } else {
                Iterator<PGPSecretKey> keyIterator = keyRing.getSecretKeys();

                while (keyIterator.hasNext()) {
                    secretKey = keyIterator.next();
                    try {
                        return secretKey.extractPrivateKey(decryptor);
                    } catch (Exception e) {
                        // TODO: Log (expected) failures?
                    }
                }
            }
        }
    }

    // If this point is reached, no private key could be extracted with the given passphrase
    throw new PGPException("No private key available using passphrase");
}

From source file:org.m1theo.apt.repo.signing.PGPSigner.java

License:Apache License

/**
 * Returns the secret key matching the specified identifier.
 *
 * @param input the input stream containing the keyring collection
 * @param keyId the 4 bytes identifier of the key
 *//*from   w  ww. jav  a2 s  .co  m*/
private PGPSecretKey getSecretKey(InputStream input, String keyId) throws IOException, PGPException {
    PGPSecretKeyRingCollection keyrings = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(input),
            new JcaKeyFingerprintCalculator());

    Iterator rIt = keyrings.getKeyRings();

    while (rIt.hasNext()) {
        PGPSecretKeyRing kRing = (PGPSecretKeyRing) rIt.next();
        Iterator kIt = kRing.getSecretKeys();

        while (kIt.hasNext()) {
            PGPSecretKey key = (PGPSecretKey) kIt.next();

            if (key.isSigningKey()
                    && String.format("%08x", key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) {
                return key;
            }
        }
    }

    return null;
}

From source file:ubicrypt.core.crypto.PGPKeyRingImpl.java

License:Open Source License

private void readPrivateKeyBundle() throws Exception {
    final InputStream in = new FileInputStream(getSecretKeyRingFileName());
    final PGPSecretKeyRingCollection collection = new PGPSecretKeyRingCollection(in,
            new BcKeyFingerprintCalculator());
    in.close();//from ww  w.  j  av  a 2 s  . c  om
    final Iterator iter = collection.getKeyRings();
    while (iter.hasNext()) {
        final PGPSecretKeyRing sec = (PGPSecretKeyRing) iter.next();
        final Iterator userids = sec.getPublicKey().getUserIDs();
        while (userids.hasNext()) {
            final String uid = (String) userids.next();
        }
    }
    secretKey = collection.getSecretKey(Long.valueOf(getSecretAliasId()));

    if (secretKey == null) {
        final StringBuilder message = new StringBuilder();
        message.append('\n');
        final Iterator iterator = collection.getKeyRings();
        while (iterator.hasNext()) {
            final PGPSecretKeyRing ring = (PGPSecretKeyRing) iterator.next();
            final Iterator secretKeysIterator = ring.getSecretKeys();
            while (secretKeysIterator.hasNext()) {
                final PGPSecretKey k = (PGPSecretKey) secretKeysIterator.next();
                message.append("Key: ");
                message.append(k.getKeyID());
                message.append('\n');
            }
        }
        throw new Exception("no secret found but available:" + message.toString());
    }
}