Example usage for org.bouncycastle.openpgp PGPPublicKeyRingCollection PGPPublicKeyRingCollection

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

Introduction

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

Prototype

public PGPPublicKeyRingCollection(Collection<PGPPublicKeyRing> collection) throws IOException, PGPException 

Source Link

Usage

From source file:SELSKeyGen.java

License:Open Source License

private static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {
    in = PGPUtil.getDecoderStream(in);//  w  ww  . jav  a 2  s . c o  m

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);

    //
    // 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.
    //
    Iterator rIt = pgpPub.getKeyRings();

    while (key == null && rIt.hasNext()) {
        PGPPublicKeyRing kRing = (PGPPublicKeyRing) rIt.next();
        Iterator kIt = kRing.getPublicKeys();
        //boolean                        encryptionKeyFound = false;

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

            if (k.isEncryptionKey()) {
                key = k;
            }
        }
    }

    if (key == null) {
        throw new IllegalArgumentException("Can't find encryption key in key ring.");
    }

    return key;
}

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

License:Apache License

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

    try {//from   w w w .  j  a  v  a2s  . c o m
        final File keyFile = this.publicKeyRing;

        final InputStream in = PGPUtil.getDecoderStream(inputStream);

        PGPObjectFactory pgpFact = new PGPObjectFactory(in);

        final PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject();

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

        final PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) pgpFact.nextObject();

        final PGPOnePassSignature ops = p1.get(0);

        final PGPLiteralData p2 = (PGPLiteralData) pgpFact.nextObject();

        final InputStream dIn = p2.getInputStream();
        int ch;
        final PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(new FileInputStream(keyFile)));

        final PGPPublicKey key = pgpRing.getPublicKey(ops.getKeyID());

        ops.init(new BcPGPContentVerifierBuilderProvider(), key);

        while ((ch = dIn.read()) >= 0) {
            ops.update((byte) ch);
            outputStream.write(ch);
        }

        outputStream.close();

        final PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();

        if (!ops.verify(p3.get(0))) {
            outputStream = null;
        }
    } catch (final FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final SignatureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final PGPException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

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

License:Apache License

@Override
public void importCryptographyMetadata(final InputStream input) {

    OpenPGPSecurityUtility.LOGGER.info("Importing cryptography metadata");
    try {/*from   w w  w. j a va  2s . c  o m*/
        PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(new FileInputStream(this.publicKeyRing)));

        final PGPPublicKeyRingCollection pgpPubIncoming = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(input));

        PGPPublicKeyRing ppKr;
        final Iterator<PGPPublicKeyRing> it = pgpPubIncoming.getKeyRings();
        while (it.hasNext()) {
            ppKr = it.next();
            if (!pgpPub.contains(ppKr.getPublicKey().getKeyID())) {
                pgpPub = PGPPublicKeyRingCollection.addPublicKeyRing(pgpPub, ppKr);
            }
        }

        pgpPub.encode(new FileOutputStream(new File(this.publicKeyRing.getAbsolutePath())));
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final PGPException e) {
        e.printStackTrace();
    }

}

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.//www .  j  av a 2s.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

public PGPPublicKeyRingCollection readPublicKeyRingCollection(InputStream keyRingCollectionIn)
        throws IOException, FileNotFoundException, PGPException {
    InputStream in = PGPUtil.getDecoderStream(keyRingCollectionIn);

    PGPPublicKeyRingCollection retval = new PGPPublicKeyRingCollection(in);

    in.close();/*from   w w w .  j a  v  a 2  s . c  o m*/
    keyRingCollectionIn.close();

    return retval;
}

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

License:Open Source License

/**
 * Encrypt and sign the specified input file.  If you pass in a seed, you
 * will get the same encrypted output for the same file + same seed + same signor.
 * //from w ww  . j a v a2  s  .  c  o m
 * DANGER!  If you use the same seed for multiple different messages, you are
 * making your key stream vulnerable to hacking, and your encryption is near
 * meaningless!  Make sure to use different seeds for different contents!
 *  
 * @param seed 
 */
public void encryptAndSignFile(String outputFilename, File inFile, InputStream publicRing,
        InputStream secretRing, String recipient, String signor, char[] passwd, boolean armor,
        boolean withIntegrityCheck, boolean oldFormat, byte[] seed) throws PGPException {
    try {
        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing);

        // Find the recipient's key
        PGPPublicKey encKey = readPublicKey(pubRing, recipient, true);
        if (encKey.isRevoked()) {
            String keyId = Long.toHexString(encKey.getKeyID()).substring(8);
            throw new PGPException("Encryption key (0x" + keyId + ") has been revoked");
        }

        // Find the signing key
        PGPPublicKey publicKey;
        PGPSecretKey secretKey;
        if (signor != null) {
            publicKey = readPublicKey(pubRing, signor, false);
            secretKey = findSecretKey(secRing, publicKey.getKeyID(), true);
        } else {
            // Just look for the first signing key on the secret keyring (if any)
            secretKey = findSigningKey(secRing);
            publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false);
        }
        if (publicKey.isRevoked()) {
            String keyId = Long.toHexString(publicKey.getKeyID()).substring(8);
            throw new PGPException("Signing key (0x" + keyId + ") has been revoked");
        }

        PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC");

        // Sign the data into an in-memory stream
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        if (oldFormat) {
            signDataV3(inFile, bOut, publicKey, privateKey);
        } else {
            signData(inFile, bOut, publicKey, privateKey);
        }

        SecureRandom secRand = makeSecureRandom(seed);

        PGPEncryptedDataGenerator cPk = oldFormat
                ? new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, secRand, oldFormat, "BC")
                : new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, withIntegrityCheck, secRand, "BC");

        cPk.addMethod(encKey);

        byte[] bytes = bOut.toByteArray();

        OutputStream out = new FileOutputStream(outputFilename);
        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;
        OutputStream cOut = cPk.open(aOut, bytes.length);

        cOut.write(bytes);

        cPk.close();

        if (armor) {
            aOut.close();
        }
        out.close();
    } catch (PGPException e) {
        throw e;
    } catch (Exception e) {
        throw new PGPException("Error in encryption", e);
    }
}

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

License:Open Source License

/**
 * Sign the specified file/*  w  w  w  .  j av  a2s . com*/
 */
public void signFile(String outputFilename, File inFile, InputStream publicRing, InputStream secretRing,
        String signor, char[] passwd, boolean armor, boolean oldFormat) throws PGPException {
    try {
        PGPPublicKey publicKey;
        PGPSecretKey secretKey;

        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        PGPSecretKeyRingCollection secRing = readSecretKeyRingCollection(secretRing);

        // Find the signing key
        if (signor != null) {
            publicKey = readPublicKey(pubRing, signor, false);
            secretKey = findSecretKey(secRing, publicKey.getKeyID(), true);
        } else {
            // Just look for the first signing key on the secret keyring (if any)
            secretKey = findSigningKey(secRing);
            publicKey = findPublicKey(pubRing, secretKey.getKeyID(), false);
        }
        if (publicKey.isRevoked()) {
            String keyId = Long.toHexString(publicKey.getKeyID()).substring(8);
            throw new PGPException("Signing key (0x" + keyId + ") has been revoked");
        }

        PGPPrivateKey privateKey = secretKey.extractPrivateKey(passwd, "BC");

        OutputStream out = new FileOutputStream(outputFilename);
        OutputStream aOut = armor ? new ArmoredOutputStream(out) : out;

        // Sign the data
        if (oldFormat) {
            signDataV3(inFile, aOut, publicKey, privateKey);
        } else {
            signData(inFile, aOut, publicKey, privateKey);
        }

        if (armor) {
            // close() just finishes and flushes the stream but does not close it
            aOut.close();
        }
        out.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

/**
 * Verify the passed in file as being correctly signed.
 *//*from  ww w . j a  v  a 2  s .  com*/
public void verifyFile(OutputStream out, InputStream inFile, InputStream publicRing) throws PGPException {
    try {
        // Get the public keyring
        PGPPublicKeyRingCollection pubRing = new PGPPublicKeyRingCollection(
                PGPUtil.getDecoderStream(publicRing));

        InputStream in = PGPUtil.getDecoderStream(inFile);

        //
        // a clear signed file
        //
        if (in instanceof ArmoredInputStream && ((ArmoredInputStream) in).isClearText()) {
            if (!checkClearsign(in, pubRing)) {
                throw new PGPException("Signature verification failed.");
            }

            if (_verbose) {
                System.out.println("Signature verified.");
            }
        } else {
            PGPObjectFactory pgpFact = new PGPObjectFactory(in);

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

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

            Object message = pgpFact.nextObject();

            if (message instanceof PGPOnePassSignatureList) {
                // One-pass signature list
                if (!checkOnePassSignature(out, (PGPOnePassSignatureList) message, pgpFact, pubRing)) {
                    throw new PGPException("Signature verification failed.");
                }
            } else if (message instanceof PGPSignatureList) {
                // Signature list
                if (!checkSignature(out, (PGPSignatureList) message, pgpFact, pubRing)) {
                    throw new PGPException("Signature verification failed.");
                }
            } else {
                // what?
                throw new PGPException("Unrecognised PGP message type");
            }
        }
        if (_verbose) {
            System.out.println("Signature verified.");
        }
    } catch (Exception e) {
        throw new PGPException("Error in verification", e);
    }
}

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  w  w  w . j a va  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

@SuppressWarnings("unchecked")
public static PGPPublicKey readPublicKey(InputStream in) throws IOException, PGPException {
    in = PGPUtil.getDecoderStream(in);//from w w  w. ja va  2 s  . c o  m

    PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(in);

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

    //
    // iterate through the key rings.
    //
    Iterator<PGPPublicKeyRing> rIt = pgpPub.getKeyRings();

    while (rIt.hasNext()) {
        PGPPublicKeyRing kRing = rIt.next();
        Iterator<PGPPublicKey> kIt = kRing.getPublicKeys();

        while (kIt.hasNext()) {
            PGPPublicKey k = kIt.next();
            if (k.isEncryptionKey()) {
                return k;
            }
        }
    }

    throw new IllegalArgumentException("Can't find encryption key in key ring.");
}