Example usage for org.bouncycastle.openssl PEMEncryptedKeyPair decryptKeyPair

List of usage examples for org.bouncycastle.openssl PEMEncryptedKeyPair decryptKeyPair

Introduction

In this page you can find the example usage for org.bouncycastle.openssl PEMEncryptedKeyPair decryptKeyPair.

Prototype

public PEMKeyPair decryptKeyPair(PEMDecryptorProvider keyDecryptorProvider) throws IOException 

Source Link

Usage

From source file:co.lqnt.lockbox.key.KeyFactory.java

License:Open Source License

/**
 * Decrypts an encrypted PEM key pair./*  www  .  ja v  a2s.  c om*/
 *
 * @param encryptedKeyPair The key pair to decrypt.
 * @param password         The password to use.
 *
 * @return The decrypted private key.
 * @throws PrivateKeyReadException If reading of the private key fails.
 */
protected PrivateKey decryptPemKeyPair(PEMEncryptedKeyPair encryptedKeyPair, String password)
        throws PrivateKeyReadException {
    PEMDecryptorProvider decryptorProvider = this.pemDecryptorProviderBuilder().build(password.toCharArray());

    PEMKeyPair pemKeyPair;
    try {
        pemKeyPair = encryptedKeyPair.decryptKeyPair(decryptorProvider);
    } catch (IOException e) {
        throw new PrivateKeyReadException(e);
    }

    return this.convertPrivateKey(pemKeyPair.getPrivateKeyInfo());
}

From source file:com.google.examples.JOSEToolBase.java

License:Apache License

public static PrivateKey decodePrivateKey(String privateKeyString, String password) throws KeyParseException {
    try {/*from ww w  .java 2s  .com*/
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        privateKeyString = reformIndents(privateKeyString);
        PEMParser pemParser = new PEMParser(new StringReader(privateKeyString));
        Object object = pemParser.readObject();
        if (object == null) {
            throw new KeyParseException("unable to read anything when decoding private key");
        }

        KeyPair kp = null;

        //LOGGER.info(String.format("decodePrivateKey, %s", object.getClass().getName()));
        if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            // produced by "openssl genpkey" or  the series of commands reqd to sign an ec key
            //LOGGER.info("decodePrivateKey, encrypted PrivateKeyInfo");
            PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
            JceOpenSSLPKCS8DecryptorProviderBuilder decryptorProviderBuilder = new JceOpenSSLPKCS8DecryptorProviderBuilder();
            InputDecryptorProvider decryptorProvider = decryptorProviderBuilder.build(password.toCharArray());
            PrivateKeyInfo privateKeyInfo = pkcs8EncryptedPrivateKeyInfo
                    .decryptPrivateKeyInfo(decryptorProvider);
            return (PrivateKey) converter.getPrivateKey(privateKeyInfo);
        }

        if (object instanceof PrivateKeyInfo) {
            // produced by openssl genpkey without encryption
            return (PrivateKey) converter.getPrivateKey((PrivateKeyInfo) object);
        }

        if (object instanceof PEMEncryptedKeyPair) {
            // produced by "openssl genrsa" or "openssl ec -genkey"
            // LOGGER.info("decodePrivateKey, encrypted keypair");
            PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) object;
            PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder()
                    .build(password.toCharArray());
            kp = converter.getKeyPair(encryptedKeyPair.decryptKeyPair(decryptorProvider));
        } else if (object instanceof PEMKeyPair) {
            //LOGGER.info("decodePrivateKey, un-encrypted keypair");
            PEMKeyPair unencryptedKeyPair = (PEMKeyPair) object;
            kp = converter.getKeyPair(unencryptedKeyPair);
        } else {
            //LOGGER.error("decodePrivateKey, unknown object type {}", object.getClass().getName());
            throw new KeyParseException("unknown object type when decoding private key");
        }

        return (PrivateKey) kp.getPrivate();
    } catch (KeyParseException exc0) {
        throw exc0;
    } catch (Exception exc1) {
        throw new KeyParseException("cannot instantiate private key", exc1);
    }
}

From source file:com.joyent.http.signature.KeyPairLoader.java

License:Open Source License

/**
 * Read KeyPair from an input stream, optionally using password and desired Security Provider. Most implementations
 * should continue calling the one and two-argument methods
 *
 * @param is       private key content as a stream
 * @param password password associated with key
 * @param provider security provider to use when loading the key
 * @return public/private keypair object
 * @throws IOException If unable to read the private key from the string
 *///from  www  . ja  v a 2s .co m
public static KeyPair getKeyPair(final InputStream is, final char[] password,
        final DesiredSecurityProvider provider) throws IOException {
    final Object pemObject;
    try (InputStreamReader isr = new InputStreamReader(is, StandardCharsets.US_ASCII);
            BufferedReader br = new BufferedReader(isr);
            PEMParser pemParser = new PEMParser(br)) {

        pemObject = pemParser.readObject();
    }

    final PEMKeyPair pemKeyPair;

    if (pemObject instanceof PEMEncryptedKeyPair) {
        if (password == null) {
            throw new KeyLoadException("Loaded key is encrypted but no password was supplied.");
        }

        final PEMDecryptorProvider decryptorProvider = new JcePEMDecryptorProviderBuilder().build(password);
        final PEMEncryptedKeyPair encryptedPemObject = ((PEMEncryptedKeyPair) pemObject);
        pemKeyPair = encryptedPemObject.decryptKeyPair(decryptorProvider);
    } else if (pemObject instanceof PEMKeyPair) {
        if (password != null) {
            throw new KeyLoadException("Loaded key is not encrypted but a password was supplied.");
        }

        pemKeyPair = (PEMKeyPair) pemObject;
    } else if (pemObject == null) {
        throw new KeyLoadException("Failed to load PEM object, please verify the input is a private key");
    } else {
        throw new KeyLoadException("Unexpected PEM object loaded: " + pemObject.getClass().getCanonicalName());
    }

    // throw if the user has specifically requested NSS and it is unavailable
    if (provider != null && provider.equals(DesiredSecurityProvider.NSS) && CONVERTER_PKCS11_NSS == null) {
        throw new KeyLoadException(PROVIDER_PKCS11_NSS + " provider requested but unavailable. "
                + "Is java.security configured correctly?");
    }

    // Attempt to load with NSS if it is available and requested (or no provider was specified)
    final boolean attemptPKCS11NSS = provider == null || provider.equals(DesiredSecurityProvider.NSS);

    if (CONVERTER_PKCS11_NSS != null && attemptPKCS11NSS) {
        return CONVERTER_PKCS11_NSS.getKeyPair(pemKeyPair);
    }

    return CONVERTER_BOUNCY_CASTLE.getKeyPair(pemKeyPair);
}

From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastleStoreProvider.java

License:Open Source License

private KeyPair keyFromPEMObject(Object pemObject, PasswordCallback password, String resource)
        throws IOException {
    PEMKeyPair keyPair = null;/* w  w  w.j av a  2 s  . c o m*/

    if (pemObject instanceof PEMEncryptedKeyPair) {
        PEMEncryptedKeyPair encryptedKeyPair = (PEMEncryptedKeyPair) pemObject;
        JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
        String passwordInput = (password != null ? password.queryPassword(resource) : null);
        Exception invalidPasswordException = null;

        while (keyPair == null) {
            if (passwordInput == null) {
                throw new PasswordRequiredException("Password required for PEM object: '" + resource + "'",
                        invalidPasswordException);
            }

            assert password != null;

            PEMDecryptorProvider decryptorProvider = decryptorBuilder.build(passwordInput.toCharArray());

            try {
                keyPair = encryptedKeyPair.decryptKeyPair(decryptorProvider);
            } catch (EncryptionException e) {
                invalidPasswordException = e;
                passwordInput = password.requeryPassword(resource, e);
            }
        }
    } else {
        keyPair = (PEMKeyPair) pemObject;
    }

    JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter();

    return keyConverter.getKeyPair(keyPair);
}

From source file:jenkins.bouncycastle.api.PEMEncodable.java

License:Open Source License

/**
 * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String}
 * //from w w  w.ja v a  2s .c  om
 * @param pem {@link String} with the PEM data
 * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller
 * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with
 * <code>Arrays.fill(passphrase, (char)0)</code>
 * @return {@link PEMEncodable} object
 * @throws IOException launched if a problem exists reading the PEM information
 * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided
 */
@Nonnull
public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase)
        throws IOException, UnrecoverableKeyException {

    try (PEMParser parser = new PEMParser(new StringReader(pem));) {

        Object object = parser.readObject();

        JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC");

        // handle supported PEM formats.
        if (object instanceof PEMEncryptedKeyPair) {
            if (passphrase != null) {
                PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase);
                PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object;
                return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (passphrase != null) {
                InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase);
                PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object;
                return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PEMKeyPair) {
            return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object));
        } else if (object instanceof PrivateKeyInfo) {
            PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object);

            // JENKINS-35661 in this case we know how to get the public key too
            if (pk instanceof RSAPrivateCrtKey) {
                // obtain public key spec from the private key
                RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk;
                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(),
                        rsaPK.getPublicExponent());
                KeyFactory kf = KeyFactory.getInstance("RSA");
                return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK));
            }

            return new PEMEncodable(pk);
        } else if (object instanceof SubjectPublicKeyInfo) {
            return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object));
        } else if (object instanceof X509CertificateHolder) {
            JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC");
            return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object));
        } else {
            throw new IOException(
                    "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received "
                            + object.getClass().getName());
        }
    } catch (OperatorCreationException e) {
        throw new IOException(e.getMessage(), e);
    } catch (PKCSException | InvalidKeySpecException e) {
        LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e);
        throw new UnrecoverableKeyException();
    } catch (CertificateException e) {
        throw new IOException("Could not read certificate", e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(
                "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html");
    }
}

From source file:net.adamcin.httpsig.ssh.bc.PEMUtil.java

License:Open Source License

/**
 * Read a single PEM-formatted key/*from   ww  w.  ja  v  a 2  s.c  om*/
 * @param is
 * @param passphrase
 * @return
 * @throws IOException
 */
public static Key readKey(InputStream is, final char[] passphrase) throws IOException {
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
    PEMParser parser = null;
    KeyPair keyPair = null;

    try {
        parser = new PEMParser(new InputStreamReader(is));

        Object o = parser.readObject();
        if (o instanceof PEMEncryptedKeyPair) {
            PEMEncryptedKeyPair _encPair = (PEMEncryptedKeyPair) o;
            PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder().build(passphrase);
            keyPair = converter.getKeyPair(_encPair.decryptKeyPair(decryptionProv));
        } else if (o instanceof PEMKeyPair) {
            keyPair = converter.getKeyPair((PEMKeyPair) o);
        }

        if (keyPair != null) {
            if (keyPair.getPrivate() instanceof RSAPrivateKey || keyPair.getPublic() instanceof RSAPublicKey) {
                return new SSHKey(KeyFormat.SSH_RSA, keyPair);
            } else if (keyPair.getPrivate() instanceof DSAPrivateKey
                    || keyPair.getPublic() instanceof DSAPublicKey) {
                return new SSHKey(KeyFormat.SSH_DSS, keyPair);
            }
        }

        return null;

    } finally {
        if (parser != null) {
            try {
                parser.close();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:net.adamcin.httpsig.testutil.KeyTestUtil.java

License:Open Source License

public static KeyPair getPrivateKeyAsKeyPair(String parentName, String keyName, final String passphrase) {
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter();

    File privateKeyFile = getPrivateKeyAsFile(parentName, keyName);
    InputStream is = null;//from w  ww.  jav  a 2 s .co m
    PEMParser parser = null;
    try {
        is = new FileInputStream(privateKeyFile);
        parser = new PEMParser(new InputStreamReader(is));

        Object o = parser.readObject();
        if (o instanceof PEMEncryptedKeyPair) {
            PEMEncryptedKeyPair _encPair = (PEMEncryptedKeyPair) o;
            PEMDecryptorProvider decryptionProv = new JcePEMDecryptorProviderBuilder()
                    .build(passphrase.toCharArray());
            return converter.getKeyPair(_encPair.decryptKeyPair(decryptionProv));
        } else if (o instanceof PEMKeyPair) {
            return converter.getKeyPair((PEMKeyPair) o);
        }
    } catch (Exception e) {
        LOGGER.error("failed to parse private key file: parent=" + parentName + " keyName=" + keyName, e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(parser);
    }

    return null;
}

From source file:org.candlepin.pki.PrivateKeyReaderTest.java

License:Open Source License

@Test
public void testReadEncryptedPKCS1() throws Exception {
    String keyFile = "keys/pkcs1-aes256-encrypted.pem";
    try (InputStream keyStream = cl.getResourceAsStream(keyFile);
            Reader expectedReader = new InputStreamReader(cl.getResourceAsStream(keyFile));) {
        PrivateKey actualKey = new PrivateKeyReader().read(keyStream, "password");
        PEMEncryptedKeyPair expected = (PEMEncryptedKeyPair) new PEMParser(expectedReader).readObject();

        PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().setProvider(BC_PROVIDER)
                .build(PASSWORD);//w  ww  . j a  va 2 s.  c om

        PEMKeyPair decryptedInfo = expected.decryptKeyPair(provider);
        PrivateKey expectedKey = new JcaPEMKeyConverter().setProvider(BC_PROVIDER).getKeyPair(decryptedInfo)
                .getPrivate();
        assertEquals(actualKey, expectedKey);
    }
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

License:Open Source License

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;//from ww  w .  jav  a  2  s .  com
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.info(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.info("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:org.commonjava.util.jhttpc.INTERNAL.util.BouncyCastleUtils.java

License:Apache License

public static KeyStore readKeyAndCertFromPem(String pemContent, String keyPass)
        throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, JHttpCException {
    Logger logger = LoggerFactory.getLogger(BouncyCastleUtils.class);

    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*from w w  w  .j ava 2  s.co m*/

    //        final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
    //                KeyManagerFactory.getDefaultAlgorithm());
    //
    //        kmfactory.init(ks, keyPass.toCharArray());

    //        final CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );

    //        Pattern keyTypePattern = Pattern.compile( KEY_TYPE_PATTERN );
    //        Matcher matcher = keyTypePattern.matcher( pemContent );

    //        String keyType = "RSA";
    //        if ( matcher.find() )
    //        {
    //            String type = matcher.group( 1 );
    //            if ( "ENCRYPTED".equals( type ) )
    //            {
    //                keyType = "PKCS8";
    //            }
    //            else
    //            {
    //                keyType = type;
    //            }
    //        }
    //
    //        logger.trace( "Using key factory for type: {}", keyType );
    //        final KeyFactory keyFactory = KeyFactory.getInstance( keyType );

    //        final List<String> lines = SSLUtils.readLines( pemContent );
    //
    //        String currentHeader = null;
    //        final StringBuilder current = new StringBuilder();

    int certIdx = 0;

    BouncyCastleProvider bcProvider = new BouncyCastleProvider();
    InputDecryptorProvider provider = new JcePKCSPBEInputDecryptorProviderBuilder().setProvider(bcProvider)
            .build(keyPass.toCharArray());

    final List<Certificate> certs = new ArrayList<Certificate>();
    PrivateKey key = null;

    PEMParser pemParser = new PEMParser(new StringReader(pemContent));
    Object pemObj = null;
    while ((pemObj = pemParser.readObject()) != null) {
        logger.trace("Got PEM object: {}", pemObj);
        if (pemObj instanceof X509CertificateHolder) {
            X509CertificateHolder holder = (X509CertificateHolder) pemObj;
            X509Certificate certificate = new JcaX509CertificateConverter().setProvider(bcProvider)
                    .getCertificate(holder);

            certs.add(certificate);

            Set<String> aliases = new HashSet<String>();
            aliases.add("certificate" + certIdx);

            extractAliases(certificate, aliases);

            KeyStore.TrustedCertificateEntry ksEntry = new KeyStore.TrustedCertificateEntry(certificate);
            for (String alias : aliases) {
                ks.setEntry(alias, ksEntry, null);
                logger.trace("Storing trusted cert under alias: {}\n  with DN: {}", alias,
                        certificate.getSubjectDN().getName());
            }

            certIdx++;
        } else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {
            PKCS8EncryptedPrivateKeyInfo keyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
            PrivateKeyInfo privateKeyInfo = null;
            try {
                privateKeyInfo = keyInfo.decryptPrivateKeyInfo(provider);
            } catch (PKCSException e) {
                throw new JHttpCException("Failed to decrypt key/certificate: %s", e, e.getMessage());
            }
            key = new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
        } else if (pemObj instanceof PEMEncryptedKeyPair) {
            PEMEncryptedKeyPair keyPair = (PEMEncryptedKeyPair) pemObj;
            PEMKeyPair decryptedKeyPair = keyPair
                    .decryptKeyPair(new BcPEMDecryptorProvider(keyPass.toCharArray()));
            PrivateKeyInfo privateKeyInfo = decryptedKeyPair.getPrivateKeyInfo();
            key = new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
        } else {
            logger.trace("Got unrecognized PEM object: {} (class: {})", pemObj,
                    (pemObj == null ? "NULL" : pemObj.getClass().getName()));
        }

        logger.trace("Got private key:\n{}\n", key);
    }

    if (key != null && !certs.isEmpty()) {
        logger.trace("Setting key entry: {}", key);
        ks.setKeyEntry(MonolithicKeyStrategy.KEY, key, keyPass.toCharArray(),
                certs.toArray(new Certificate[certs.size()]));
    } else {
        logger.warn("No private key found in PEM!");
    }

    return ks;
}