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(Collection<PGPSecretKeyRing> collection) throws IOException, PGPException 

Source Link

Usage

From source file:SELSKeyGen.java

License:Open Source License

/**
 * Load a secret key ring collection from keyIn and find the secret key corresponding to
 * keyID if it exists./*from w ww  .  ja v  a 2  s .  c o  m*/
 * 
 * @param keyIn input stream representing a key ring collection.
 * @param keyID keyID we want.
 * @param pass passphrase to decrypt secret key with.
 * @return
 * @throws IOException
 * @throws PGPException
 * @throws NoSuchProviderException
 */
private static PGPPrivateKey findSecretKey(InputStream keyIn, long keyID, char[] pass)
        throws IOException, PGPException, NoSuchProviderException {
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));

    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);

    if (pgpSecKey == null) {
        return null;
    }

    return pgpSecKey.extractPrivateKey(pass, "BC");
}

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

License:Apache License

@Override
public void decrypt(final OutputStream outputStream, final InputStream inputStream) {

    try {//w  w w.  ja  v a2 s.co  m
        final File keyFile = this.secretKeyRing;
        final char[] passwd = this.secretKeyRingPassword;

        final InputStream in = PGPUtil.getDecoderStream(inputStream);

        try {
            final PGPObjectFactory pgpF = new PGPObjectFactory(in);
            PGPEncryptedDataList enc;

            final Object o = pgpF.nextObject();

            if (o instanceof PGPEncryptedDataList) {
                enc = (PGPEncryptedDataList) o;
            } else {
                enc = (PGPEncryptedDataList) pgpF.nextObject();
            }

            final Iterator it = enc.getEncryptedDataObjects();
            PGPPrivateKey sKey = null;
            PGPPublicKeyEncryptedData pbe = null;
            final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
                    PGPUtil.getDecoderStream(new FileInputStream(keyFile)));

            while ((sKey == null) && it.hasNext()) {
                pbe = (PGPPublicKeyEncryptedData) it.next();

                sKey = this.findSecretKey(pgpSec, pbe.getKeyID(), passwd);
            }

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

            final InputStream clear = pbe.getDataStream(new BcPublicKeyDataDecryptorFactory(sKey));

            final PGPObjectFactory plainFact = new PGPObjectFactory(clear);

            final PGPCompressedData cData = (PGPCompressedData) plainFact.nextObject();

            final InputStream compressedStream = new BufferedInputStream(cData.getDataStream());
            final PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream);

            final Object message = pgpFact.nextObject();

            if (message instanceof PGPLiteralData) {
                final PGPLiteralData ld = (PGPLiteralData) message;

                final InputStream unc = ld.getInputStream();
                final OutputStream fOut = new BufferedOutputStream(outputStream);

                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.");
        } catch (final PGPException e) {
            System.err.println(e);
            if (e.getUnderlyingException() != null) {
                e.getUnderlyingException().printStackTrace();
            }
        }
    } catch (final FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

License:Apache License

/**
 * Gets the correct signing key from local secret keyring using the supplied
 * key information./*from ww  w  .  j a  va 2  s  .c  om*/
 * 
 * @param keyInfo
 *            the supplied key information
 * @return the correct signing key
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws PGPException
 *             thrown if an error is encountered
 */
public PGPSecretKey getSignKey(final String keyInfo) throws IOException, PGPException {
    final PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(
            PGPUtil.getDecoderStream(new FileInputStream(this.secretKeyRing)));

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

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

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

        }
    }

    return null;
}

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

License:Open Source License

public PGPSecretKeyRingCollection readSecretKeyRingCollection(File secretRing)
        throws IOException, PGPException {
    InputStream secretRingStream = new FileInputStream(secretRing);
    PGPSecretKeyRingCollection secRing = new PGPSecretKeyRingCollection(
            PGPUtil.getDecoderStream(secretRingStream));
    secretRingStream.close();/*from  w ww.  java  2  s.  c o  m*/
    return secRing;
}

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

License:Open Source License

public PGPSecretKeyRingCollection readSecretKeyRingCollection(InputStream secretRing)
        throws IOException, PGPException {
    PGPSecretKeyRingCollection secRing = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(secretRing));
    return secRing;
}

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

License:Open Source License

/**
 * Get the keyring pointed to by the public & secret files.  Creates the files
 * with a single key if they don't already exist; interrogates keyDataSource for the
 * info to create the key (typically it should pop up a gui).
 * /*from ww w.j ava  2  s . c  om*/
 * TODO bobby: doesn't create usable keyrings yet, and doesn't save what it does create :-( 
 * @param publicKeyRingFile
 * @param secretKeyRingFile
 * @param keyDataSource
 * @return
 * @throws PGPException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 */
public Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection> getOrCreateKeyring(File publicKeyRingFile,
        File secretKeyRingFile, KeyDataSource keyDataSource) throws PGPException, FileNotFoundException,
        IOException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    boolean pubRingFound = publicKeyRingFile.isFile();
    boolean secRingFound = secretKeyRingFile.isFile();

    if (pubRingFound != secRingFound) {
        throw new PGPException("Expect both public & secret keyring, or neither: " + publicKeyRingFile + ", "
                + secretKeyRingFile);
    }

    Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection> retval = new Pair<PGPPublicKeyRingCollection, PGPSecretKeyRingCollection>();

    if (pubRingFound) {
        retval.setFirst(EncryptionUtil.instance().readPublicKeyRingCollection(publicKeyRingFile));
        retval.setSecond(EncryptionUtil.instance().readSecretKeyRingCollection(secretKeyRingFile));
    } else {
        if (publicKeyRingFile.exists() || secretKeyRingFile.exists()) {
            throw new PGPException("Either public or secret keyring not a normal file: " + publicKeyRingFile
                    + ", " + secretKeyRingFile);
        }

        PGPSecretKey key = generateKey(keyDataSource.getIdentity(), keyDataSource.getPassphrase());

        PGPPublicKeyRing publicKeyRing = new PGPPublicKeyRing(key.getPublicKey().getEncoded());
        Collection<PGPPublicKeyRing> collection = Collections.singletonList(publicKeyRing);
        retval.setFirst(new PGPPublicKeyRingCollection(collection));

        PGPSecretKeyRing secretKeyRing = new PGPSecretKeyRing(key.getEncoded());
        Collection<PGPSecretKeyRing> secretKeyRings = Collections.singletonList(secretKeyRing);
        retval.setSecond(new PGPSecretKeyRingCollection(secretKeyRings));

        //TODO bobby save keyrings to the files
    }

    return retval;
}

From source file:com.ginema.crypto.encryption.PGPEncryption.java

License:Apache License

/**
 * decrypt the passed in message stream//from  w w w  .j  a v  a2s . c  om
 * 
 * @param encrypted The message to be decrypted.
 * @param passPhrase Pass phrase (key)
 * 
 * @return Clear text as a byte array. I18N considerations are not handled by this routine
 * @exception IOException
 * @exception PGPException
 * @exception NoSuchProviderException
 */
@SuppressWarnings("unchecked")
public static byte[] decrypt(byte[] encrypted, InputStream keyIn, char[] password)
        throws IOException, PGPException, NoSuchProviderException {

    InputStream in = PGPUtil.getDecoderStream(new ByteArrayInputStream(encrypted));

    PGPObjectFactory pgpF = new PGPObjectFactory(in);
    PGPEncryptedDataList enc = null;
    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<PGPPublicKeyEncryptedData> it = enc.getEncryptedDataObjects();
    PGPPrivateKey sKey = null;
    PGPPublicKeyEncryptedData pbe = null;
    PGPSecretKeyRingCollection pgpSec = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyIn));

    while (sKey == null && it.hasNext()) {
        pbe = it.next();

        sKey = findSecretKey(pgpSec, pbe.getKeyID(), password);
    }

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

    InputStream clear = pbe.getDataStream(sKey, "BC");

    PGPObjectFactory pgpFact = new PGPObjectFactory(clear);

    PGPCompressedData cData = (PGPCompressedData) pgpFact.nextObject();

    pgpFact = new PGPObjectFactory(cData.getDataStream());

    PGPLiteralData ld = (PGPLiteralData) pgpFact.nextObject();

    InputStream unc = ld.getInputStream();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int ch;

    while ((ch = unc.read()) >= 0) {
        out.write(ch);

    }

    byte[] returnBytes = out.toByteArray();
    out.close();
    return returnBytes;
}

From source file:com.github.sannies.nexusaptplugin.sign.PGPSigner.java

License:Apache License

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

    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()
                    && Long.toHexString(key.getKeyID() & 0xFFFFFFFFL).equals(keyId.toLowerCase())) {
                return key;
            }
        }
    }

    return null;
}

From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java

License:Apache License

/**
 * @param privateKeyFile The file that contains the private key.
 * @param privateKeyId   The ID of the key to retrieve from the file.
 *
 * @return a private key from file.//  w w  w  .  j a v a  2s . c o m
 *
 * @throws FileNotFoundException
 * @throws IOException
 * @throws PGPException
 */
@SuppressFBWarnings({ "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE" })
public static PGPSecretKey getPrivateKey(final File privateKeyFile, final long privateKeyId)
        throws IOException, PGPException {

    try (FileInputStream privateKeyInputStream = new FileInputStream(privateKeyFile)) {
        PGPSecretKeyRingCollection privateKeyRing = new PGPSecretKeyRingCollection(
                PGPUtil.getDecoderStream(privateKeyInputStream));
        return privateKeyRing.getSecretKey(privateKeyId);
    }
}

From source file:com.lyndir.lhunath.opal.crypto.gpg.GPG.java

License:Apache License

/**
 * @param privateKeyFile The file that contains the private keys.
 *
 * @return all master key IDs available in the given key ring.
 *
 * @throws FileNotFoundException//  w ww .  j av a2s.c om
 * @throws IOException
 * @throws PGPException
 */
public static List<PrintableKeyWrapper<PGPSecretKey>> getPrivateKeys(final File privateKeyFile)
        throws IOException, PGPException {

    /* Open the key ring. */
    try (FileInputStream privateKeyInputStream = new FileInputStream(privateKeyFile)) {
        List<PrintableKeyWrapper<PGPSecretKey>> keys = new ArrayList<>();
        PGPSecretKeyRingCollection privateKeyRing = new PGPSecretKeyRingCollection(
                PGPUtil.getDecoderStream(privateKeyInputStream));

        /* Enumerate the IDs. */
        @SuppressWarnings("unchecked")
        Iterator<PGPSecretKeyRing> rings = privateKeyRing.getKeyRings();
        while (rings.hasNext()) {
            @SuppressWarnings("unchecked")
            Iterator<PGPSecretKey> ring = rings.next().getSecretKeys();
            while (ring.hasNext()) {
                PGPSecretKey key = ring.next();
                if (!key.getUserIDs().hasNext())
                    continue;

                keys.add(new PrintableKeyWrapper<PGPSecretKey>(key, key.getKeyID()) {

                    @Override
                    public String toString() {

                        return getKey().getUserIDs().next().toString();
                    }
                });
            }
        }

        return keys;
    }
}