Example usage for org.bouncycastle.openpgp PGPSecretKey extractPrivateKey

List of usage examples for org.bouncycastle.openpgp PGPSecretKey extractPrivateKey

Introduction

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

Prototype

public PGPPrivateKey extractPrivateKey(PBESecretKeyDecryptor decryptorFactory) throws PGPException 

Source Link

Document

Extract a PGPPrivate key from the SecretKey's encrypted contents.

Usage

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

License:Apache License

@Override
public void sign(final OutputStream outputStream, final InputStream inputStream, final String keyInfo) {
    try {/*from w w w.jav a 2s.c  om*/
        final File keyFile = this.secretKeyRing;
        final char[] pass = this.secretKeyRingPassword;

        final ArmoredOutputStream out = new ArmoredOutputStream(outputStream);

        final PGPSecretKey pgpSec = this.getSignKey(keyInfo); // readSecretKey(new
        // FileInputStream(keyFile));
        final PGPPrivateKey pgpPrivKey = pgpSec.extractPrivateKey(
                new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider()).build(pass));
        final PGPSignatureGenerator sGen = new PGPSignatureGenerator(
                new BcPGPContentSignerBuilder(pgpSec.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1));

        sGen.init(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);

        final Iterator it = pgpSec.getPublicKey().getUserIDs();
        if (it.hasNext()) {
            final PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

            spGen.setSignerUserID(false, (String) it.next());
            sGen.setHashedSubpackets(spGen.generate());
        }

        final PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(CompressionAlgorithmTags.ZLIB);

        final BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(out));

        sGen.generateOnePassVersion(false).encode(bOut);

        final PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator();
        final byte[] buffer = new byte[1 << 16];
        final OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, "", new Date(), buffer);
        int ch = 0;

        while ((ch = inputStream.read()) >= 0) {
            lOut.write(ch);
            sGen.update((byte) ch);
        }

        lGen.close();

        sGen.generate().encode(bOut);
        cGen.close();

        out.close();
    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    } catch (final PGPException e) {
        e.printStackTrace();
    } catch (final SignatureException e) {
        e.printStackTrace();
    }
}

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

License:Apache License

/**
 * Finds the secret key of a {@link PGPSecretKeyRingCollection}.
 * /* w  w  w .  j  av  a 2s . c  o  m*/
 * @param pgpSec
 *            the {@link PGPSecretKeyRingCollection}
 * @param keyID
 *            the key id
 * @param pass
 *            the secret key password
 * @return the {@link PGPPrivateKey}
 * @throws PGPException
 *             thrown if an error is encountered
 */
private PGPPrivateKey findSecretKey(final PGPSecretKeyRingCollection pgpSec, final long keyID,
        final char[] pass) throws PGPException {
    final PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);

    if (pgpSecKey == null)
        return null;

    return pgpSecKey.extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
            .build(this.secretKeyRingPassword));
}

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

private static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection pgpSec, long keyID, char[] pass)
        throws PGPException, NoSuchProviderException {
    PGPSecretKey pgpSecKey = pgpSec.getSecretKey(keyID);

    if (pgpSecKey == null) {
        return null;
    }// ww w  . ja  va  2 s.c o  m

    return pgpSecKey.extractPrivateKey(new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(pass));
}

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

public static PGPPrivateKey getPrivateKeyFrom(PGPSecretKey secretKey) throws PGPException, IOException {
    PBESecretKeyDecryptor decryptor = new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
            .build("".toCharArray());
    return secretKey.extractPrivateKey(decryptor);
}

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

License:Apache License

static final PGPPrivateKey extractDecryptionKey(PGPSecretKeyRing pskr, String pass) throws PGPException {
    Iterator<PGPSecretKey> skit = Util.getTypedIterator(pskr.getSecretKeys(), PGPSecretKey.class);

    PGPSecretKey selected = null;

    // Pass #1 - use key flags on signatures.
    while (skit.hasNext()) {
        PGPSecretKey sk = skit.next();/*from  w  w  w  .  j a v  a 2s.c o  m*/
        Iterator<PGPSignature> sigit = Util.getTypedIterator(sk.getPublicKey().getSignatures(),
                PGPSignature.class);
        while (sigit.hasNext()) {
            if (Util.hasKeyFlag(sigit.next(), KeyFlags.ENCRYPT_COMMS | KeyFlags.ENCRYPT_STORAGE)) {
                selected = sk;
                break;
            }
        }
    }
    if (selected == null) {
        // Pass #2 - use intrinsic key capabilities, but prefer subkeys
        // where possible.
        skit = Util.getTypedIterator(pskr.getSecretKeys(), PGPSecretKey.class);
        while (skit.hasNext()) {
            PGPSecretKey sk = skit.next();
            if (sk.getPublicKey().isEncryptionKey()) {
                selected = sk;
                // But continue the loop, so subkeys will be chosen.
            }
        }
    }

    if (selected != null) {
        return selected
                .extractPrivateKey(new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
                        .build(pass.toCharArray()));
    } else {
        return null;
    }
}

From source file:com.navnorth.learningregistry.LRSigner.java

License:Apache License

/**
 * Encodes the provided message with the private key and pass phrase set in configuration
 *
 * @param message Message to encode//w  ww  .j  a  v a 2 s  . c  o m
 * @return Encoded message
 * @throws LRException SIGNING_FAILED if the document cannot be signed, NO_KEY if the key cannot be obtained
 */
private String signEnvelopeData(String message) throws LRException {
    // Throw an exception if any of the required fields are null
    if (passPhrase == null || publicKeyLocation == null || privateKey == null) {
        throw new LRException(LRException.NULL_FIELD);
    }

    // Add the provider here so that after signing, we can remove the provider.
    // This allows using this code from multiple separate class loaders while Bouncy Castle is on a separate class loader
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);

    try {

        // Get an InputStream for the private key
        InputStream privateKeyStream = getPrivateKeyStream(privateKey);

        // Get an OutputStream for the result
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        ArmoredOutputStream aOut = new ArmoredOutputStream(result);

        // Get the pass phrase
        char[] privateKeyPassword = passPhrase.toCharArray();

        try {
            // Get the private key from the InputStream
            PGPSecretKey sk = readSecretKey(privateKeyStream);
            PGPPrivateKey pk = sk.extractPrivateKey(
                    new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(privateKeyPassword));
            PGPSignatureGenerator sGen = new PGPSignatureGenerator(
                    new JcaPGPContentSignerBuilder(sk.getPublicKey().getAlgorithm(), PGPUtil.SHA256)
                            .setProvider("BC"));
            PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();

            // Clear sign the message
            java.util.Iterator it = sk.getPublicKey().getUserIDs();
            if (it.hasNext()) {
                spGen.setSignerUserID(false, (String) it.next());
                sGen.setHashedSubpackets(spGen.generate());
            }
            aOut.beginClearText(PGPUtil.SHA256);
            sGen.init(PGPSignature.CANONICAL_TEXT_DOCUMENT, pk);
            byte[] msg = message.getBytes();
            sGen.update(msg, 0, msg.length);
            aOut.write(msg, 0, msg.length);
            BCPGOutputStream bOut = new BCPGOutputStream(aOut);
            aOut.endClearText();
            sGen.generate().encode(bOut);
            aOut.close();

            String strResult = result.toString("utf8");

            // for whatever reason, bouncycastle is failing to put a linebreak before "-----BEGIN PGP SIGNATURE"
            strResult = strResult.replaceAll("([a-z0-9])-----BEGIN PGP SIGNATURE-----",
                    "$1\n-----BEGIN PGP SIGNATURE-----");

            return strResult;
        } catch (Exception e) {
            throw new LRException(LRException.SIGNING_FAILED, e);
        } finally {
            try {
                if (privateKeyStream != null) {
                    privateKeyStream.close();
                }

                result.close();
            } catch (IOException e) {
                //Could not close the streams
            }
        }
    } finally {
        Security.removeProvider(provider.getName());
    }
}

From source file:crypttools.PGPCryptoBC.java

License:Open Source License

public String signData(String data, String passphrase) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    InputStream keyInputStream = new ByteArrayInputStream(this.armoredSecretKey);
    PGPSecretKey pgpSecretKey = readSecretKey(keyInputStream);
    PGPPrivateKey pgpPrivateKey = pgpSecretKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passphrase.toCharArray()));
    PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(pgpSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                    .setProvider("BC"));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, pgpPrivateKey);

    @SuppressWarnings("unchecked")
    Iterator<String> it = pgpSecretKey.getPublicKey().getUserIDs();
    if (it.hasNext()) {
        PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator();
        spGen.setSignerUserID(false, it.next());
        signatureGenerator.setHashedSubpackets(spGen.generate());
    }//from  www.j  a  v  a2 s  .co m
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = new ArmoredOutputStream(byteOutputStream);
    PGPCompressedDataGenerator compressDataGenerator = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);
    BCPGOutputStream bcOutputStream = new BCPGOutputStream(compressDataGenerator.open(outputStream));
    signatureGenerator.generateOnePassVersion(false).encode(bcOutputStream);

    PGPLiteralDataGenerator literalDataGenerator = new PGPLiteralDataGenerator();
    File fileToSign = File.createTempFile("temp", ".scrap");
    FileUtils.writeStringToFile(fileToSign, data);

    OutputStream literalDataGenOutputStream = literalDataGenerator.open(bcOutputStream, PGPLiteralData.BINARY,
            fileToSign);
    FileInputStream fis = new FileInputStream(fileToSign);
    int ch;
    while ((ch = fis.read()) >= 0) {
        literalDataGenOutputStream.write(ch);
        signatureGenerator.update((byte) ch);
    }

    literalDataGenerator.close();
    fis.close();

    signatureGenerator.generate().encode(bcOutputStream);
    compressDataGenerator.close();
    outputStream.close();

    fileToSign.delete();
    return new String(byteOutputStream.toByteArray(), "UTF-8");
}

From source file:crypttools.PGPCryptoBC.java

License:Open Source License

public String signDataDetached(String data, String passphrase) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    InputStream keyInputStream = new ByteArrayInputStream(this.armoredSecretKey);

    PGPSecretKey pgpSecretKey = readSecretKey(keyInputStream);
    PGPPrivateKey pgpPrivateKey = pgpSecretKey.extractPrivateKey(
            new JcePBESecretKeyDecryptorBuilder().setProvider("BC").build(passphrase.toCharArray()));
    PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator(
            new JcaPGPContentSignerBuilder(pgpSecretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1)
                    .setProvider("BC"));
    signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, pgpPrivateKey);

    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = new ArmoredOutputStream(byteOutputStream);
    BCPGOutputStream bOut = new BCPGOutputStream(outputStream);

    InputStream fIn = IOUtils.toInputStream(data, "UTF-8");
    int ch;/*from  www .  ja  v  a2s .co  m*/
    while ((ch = fIn.read()) >= 0) {
        signatureGenerator.update((byte) ch);
    }

    fIn.close();

    signatureGenerator.generate().encode(bOut);

    outputStream.close();
    keyInputStream.close();

    return new String(byteOutputStream.toByteArray(), "UTF-8");
}

From source file:de.dentrassi.pm.signing.pgp.web.ServiceController.java

License:Open Source License

@ControllerValidator(formDataClass = AddEntry.class)
public void validateAdd(final AddEntry data, final ValidationContext context) {
    final String keyring = data.getKeyring();
    final File file = new File(keyring);

    if (!file.exists()) {
        context.error("keyring",
                String.format("File '%s' does not exist on the server", file.getAbsolutePath()));
        return;/*from  w  w  w. j  a  va 2 s .co m*/
    }
    if (!file.isFile()) {
        context.error("keyring", String.format("File '%s' is not a file", file.getAbsolutePath()));
        return;
    }
    if (!file.canRead()) {
        context.error("keyring", String.format("File '%s' cannot be read", file.getAbsolutePath()));
        return;
    }

    final String keyId = data.getKeyId();
    if (keyId != null) {
        try {
            try (InputStream input = new FileInputStream(file)) {
                final PGPSecretKey key = PgpHelper.loadSecretKey(input, keyId);
                if (key == null) {
                    context.error("keyId", "Key not found in keyring");
                } else if (data.getKeyPassphrase() != null) {
                    try {
                        final PGPPrivateKey privateKey = key.extractPrivateKey(
                                new BcPBESecretKeyDecryptorBuilder(new BcPGPDigestCalculatorProvider())
                                        .build(data.getKeyPassphrase().toCharArray()));
                        if (privateKey == null) {
                            Thread.sleep(1_000);
                            context.error("keyPassphrase", "Unable to unlock private key");
                        }
                    } catch (final Exception e) {
                        context.error("Failed to load key. Probably a wrong phassphrase: "
                                + ExceptionHelper.getMessage(e));
                    }
                }
            }
        } catch (final Exception e) {
            context.error("Failed to load key: " + ExceptionHelper.getMessage(e));
        }
    }
}

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

License:Apache License

/**
 * Creates the signature that will be used to PGP sign data
 *
 * @param secretKeys// ww w .  j a  v  a2  s .  com
 *                 these are the secret keys
 * @param password
 *                 this is the password to unlock the secret key
 *
 * @return the signature used to sign data
 *
 * @throws PGPException
 */
private static PGPSignatureGenerator createSignature(List<PGPSecretKey> secretKeys, char[] password,
        int signatureType, boolean generateUserIdSubPacket) throws PGPException {

    PGPSecretKey secretKey = null;
    for (int i = 0; i < secretKeys.size(); i++) {
        secretKey = secretKeys.get(i);

        // we ONLY want the signing master key
        if (!secretKey.isSigningKey() || !secretKey.isMasterKey()) {
            secretKey = null;
        }
    }

    if (secretKey == null) {
        throw new PGPException("Secret key is not the signing master key");
    }

    //            System.err.println("Signing key = " + tmpKey.isSigningKey() +", Master key = " + tmpKey.isMasterKey() + ", UserId = " +
    //                               userId );

    if (password == null) {
        password = new char[0];
    }

    PBESecretKeyDecryptor build = new BcPBESecretKeyDecryptorBuilder(digestCalculatorProvider).build(password);

    SecureRandom random = new SecureRandom();
    BcPGPContentSignerBuilder bcPGPContentSignerBuilder = new BcPGPContentSignerBuilder(
            secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1).setSecureRandom(random);

    PGPSignatureGenerator signature = new PGPSignatureGenerator(bcPGPContentSignerBuilder);
    signature.init(signatureType, secretKey.extractPrivateKey(build));

    Iterator userIds = secretKey.getPublicKey().getUserIDs();

    // use the first userId that matches
    if (userIds.hasNext()) {
        if (generateUserIdSubPacket) {
            PGPSignatureSubpacketGenerator subpacketGenerator = new PGPSignatureSubpacketGenerator();
            subpacketGenerator.setSignerUserID(false, (String) userIds.next());
            signature.setHashedSubpackets(subpacketGenerator.generate());
        } else {
            signature.setHashedSubpackets(null);
        }

        return signature;
    } else {
        throw new PGPException("Did not find specified userId");
    }
}