Example usage for org.bouncycastle.openssl PEMParser PEMParser

List of usage examples for org.bouncycastle.openssl PEMParser PEMParser

Introduction

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

Prototype

public PEMParser(Reader reader) 

Source Link

Document

Create a new PEMReader

Usage

From source file:com.spotify.sshagenttls.CertKey.java

License:Apache License

public static CertKey fromPaths(final Path certPath, final Path keyPath)
        throws IOException, GeneralSecurityException {
    // TODO (dxia) Cert might not be X.509
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");

    final Certificate cert;
    try (final InputStream is = Files.newInputStream(certPath)) {
        cert = cf.generateCertificate(is);
    }//from   w w  w .j av  a 2  s . c  om

    final Object parsedPem;
    try (final BufferedReader br = Files.newBufferedReader(keyPath, Charset.defaultCharset())) {
        parsedPem = new PEMParser(br).readObject();
    }

    final PrivateKeyInfo keyInfo;
    if (parsedPem instanceof PEMKeyPair) {
        keyInfo = ((PEMKeyPair) parsedPem).getPrivateKeyInfo();
    } else if (parsedPem instanceof PrivateKeyInfo) {
        keyInfo = (PrivateKeyInfo) parsedPem;
    } else {
        throw new UnsupportedOperationException(
                "Unable to parse X.509 certificate, received " + parsedPem.getClass());
    }

    final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyInfo.getEncoded());
    final KeyFactory kf = KeyFactory.getInstance("RSA");

    return new AutoValue_CertKey(cert, kf.generatePrivate(spec));
}

From source file:com.stormpath.spring.cloud.zuul.config.PemResourceKeyResolver.java

License:Apache License

private Key doApply(Resource resource) throws IOException, CertificateException {

    try (Reader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), "UTF-8"))) {

        PEMParser pemParser = new PEMParser(reader);

        Object o;// w w  w .j av  a 2 s .c om

        boolean encryptedPrivateFound = false;

        while ((o = pemParser.readObject()) != null) {

            if (o instanceof PKCS8EncryptedPrivateKeyInfo) {
                encryptedPrivateFound = true;
            }

            if (o instanceof PEMKeyPair) {
                PEMKeyPair pemKeyPair = (PEMKeyPair) o;
                return findPrivate ? pemKeyConverter.getPrivateKey(pemKeyPair.getPrivateKeyInfo())
                        : pemKeyConverter.getPublicKey(pemKeyPair.getPublicKeyInfo());
            }

            if (o instanceof PrivateKeyInfo && findPrivate) {
                PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) o;
                return pemKeyConverter.getPrivateKey(privateKeyInfo);
            }

            if (o instanceof SubjectPublicKeyInfo && !findPrivate) {
                SubjectPublicKeyInfo info = (SubjectPublicKeyInfo) o;
                return pemKeyConverter.getPublicKey(info);
            }

            if (o instanceof X509CertificateHolder && !findPrivate) {
                X509CertificateHolder holder = (X509CertificateHolder) o;
                X509Certificate cert = x509Converter.getCertificate(holder);
                return cert.getPublicKey();
            }
        }

        //if we haven't returned yet, we couldn't find a key based on our preferences.

        String msg;

        if (encryptedPrivateFound && findPrivate) {
            msg = "Key resource [" + resource + "] contains a PKCS8 Encrypted PrivateKey.  Only unencrypted "
                    + "private keys are supported.";
        } else {
            msg = "Key resource [" + resource + "] did not contain a " + (findPrivate ? "private " : "public ")
                    + "key.";
        }

        throw new IllegalArgumentException(msg);
    }
}

From source file:com.trustly.api.security.KeyChain.java

License:Open Source License

/**
 * Loads the merchant private key.//  w  ww.j  a v a  2s  .co  m
 * @param privateKeyFilename path to and name of private key.
 * @param password Password for the private key. "" or null if key requires no password.
 * @throws KeyException if key failed to load. For example if the path is incorrect.
 */
void loadMerchantPrivateKey(final String privateKeyFilename, final String password) throws KeyException {
    try {
        final File privateKeyFile = new File(privateKeyFilename); // private key file in PEM format
        final PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
        final Object object = pemParser.readObject();

        final PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter();

        final KeyPair kp;
        if (object instanceof PEMEncryptedKeyPair) { // Password required
            kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
        } else {
            kp = converter.getKeyPair((PEMKeyPair) object);
        }

        merchantPrivateKey = kp.getPrivate();
    } catch (final IOException e) {
        throw new KeyException("Failed to load private key", e);
    }
}

From source file:com.trustly.api.security.KeyChain.java

License:Open Source License

/**
 * Loads the Trustly public key./*w  w w .ja va  2s .  c  o m*/
 * @param testEnvironment whether to load the key for test environment or not.
 */
private void loadTrustlyPublicKey(final boolean testEnvironment) {
    try {
        final File file = testEnvironment ? new File(TEST_TRUSTLY_PUBLIC_KEY_PATH)
                : new File(LIVE_TRUSTLY_PUBLIC_KEY_PATH);

        final PEMParser pemParser = new PEMParser(new FileReader(file));
        final PemObject object = pemParser.readPemObject();

        final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(new BouncyCastleProvider());

        final byte[] encoded = object.getContent();
        final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(encoded));

        trustlyPublicKey = converter.getPublicKey(subjectPublicKeyInfo);
    } catch (final IOException e) {
        throw new TrustlyAPIException("Failed to load Trustly public key", e);
    }
}

From source file:com.vmware.admiral.common.util.CertificateUtil.java

License:Open Source License

/**
 * Utility method to decode a certificate chain PEM encoded string value to an array of X509Certificate
 * certificate instances./*from  w  w w  .  ja  v  a2s  . c  o  m*/
 *
 * @param certChainPEM
 *            - a certificate chain (one or more certificates) PEM encoded string value.
 * @return - decoded array of X509Certificate  certificate instances.
 * @throws RuntimeException
 *             if a certificate can't be decoded to X509Certificate type certificate.
 */
public static X509Certificate[] createCertificateChain(String certChainPEM) {
    AssertUtil.assertNotNull(certChainPEM, "certChainPEM should not be null.");

    List<X509Certificate> chain = new ArrayList<>();
    try (PEMParser parser = new PEMParser(new StringReader(certChainPEM))) {

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
        X509CertificateHolder certificateHolder;
        while ((certificateHolder = (X509CertificateHolder) parser.readObject()) != null) {
            chain.add(converter.getCertificate(certificateHolder));
        }
    } catch (IOException | CertificateException e) {
        throw new RuntimeException("Failed to create certificate: " + certChainPEM, e);
    }

    if (chain.isEmpty()) {
        throw new RuntimeException("A valid certificate was not found: " + certChainPEM);
    }

    return chain.toArray(new X509Certificate[chain.size()]);
}

From source file:com.vmware.admiral.common.util.CertificateUtil.java

License:Open Source License

/**
 * Utility method to decode a PEM encoded private key string to a PrivateKey instance
 *
 * @param key//ww w  .jav  a2 s  . com
 *            - a PEM encoded private key string
 * @return - decoded PrivateKey instance
 */
public static KeyPair createKeyPair(String key) {
    AssertUtil.assertNotNull(key, "key");
    String decryptedKey = EncryptionUtils.decrypt(key);
    try (PEMParser parser = new PEMParser(new StringReader(decryptedKey))) {

        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        PEMKeyPair keyPair = (PEMKeyPair) parser.readObject();
        if (keyPair == null) {
            throw new RuntimeException("A valid key pair was not found");
        }
        return converter.getKeyPair(keyPair);

    } catch (IOException e) {
        throw new RuntimeException("Failed to create key pair", e);
    }
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static X509Certificate loadX509Certificate(Reader reader) throws CryptoException {
    try (PEMParser pemParser = new PEMParser(reader)) {
        Object pemObj = pemParser.readObject();
        if (pemObj instanceof X509Certificate) {
            return (X509Certificate) pemObj;
        } else if (pemObj instanceof X509CertificateHolder) {
            try {
                return new JcaX509CertificateConverter().setProvider(BC_PROVIDER)
                        .getCertificate((X509CertificateHolder) pemObj);
            } catch (CertificateException ex) {
                LOG.error("loadX509Certificate: Caught CertificateException, unable to parse X509 certficate: "
                        + ex.getMessage());
                throw new CryptoException(ex);
            }/* w  w  w . j  a v a 2 s  .c  om*/
        }
    } catch (IOException ex) {
        LOG.error(
                "loadX509Certificate: Caught IOException, unable to parse X509 certficate: " + ex.getMessage());
        throw new CryptoException(ex);
    }

    return null;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static PrivateKey loadPrivateKey(Reader reader, String pwd) throws CryptoException {

    try (PEMParser pemReader = new PEMParser(reader)) {
        PrivateKey privKey = null;
        X9ECParameters ecParam = null;//  www.j  ava  2s  .  c o m

        Object pemObj = pemReader.readObject();

        if (pemObj instanceof ASN1ObjectIdentifier) {

            // make sure this is EC Parameter we're handling. In which case
            // we'll store it and read the next object which should be our
            // EC Private Key

            ASN1ObjectIdentifier ecOID = (ASN1ObjectIdentifier) pemObj;
            ecParam = ECNamedCurveTable.getByOID(ecOID);
            if (ecParam == null) {
                throw new PEMException("Unable to find EC Parameter for the given curve oid: "
                        + ((ASN1ObjectIdentifier) pemObj).getId());
            }

            pemObj = pemReader.readObject();

        } else if (pemObj instanceof X9ECParameters) {

            ecParam = (X9ECParameters) pemObj;
            pemObj = pemReader.readObject();
        }

        if (pemObj instanceof PEMKeyPair) {

            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) pemObj).getPrivateKeyInfo();
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(pKeyInfo);

        } else if (pemObj instanceof PKCS8EncryptedPrivateKeyInfo) {

            PKCS8EncryptedPrivateKeyInfo pKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObj;
            if (pwd == null) {
                throw new CryptoException("No password specified to decrypt encrypted private key");
            }

            // Decrypt the private key with the specified password

            InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                    .setProvider(BC_PROVIDER).build(pwd.toCharArray());

            PrivateKeyInfo privateKeyInfo = pKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            privKey = pemConverter.getPrivateKey(privateKeyInfo);
        }

        // if our private key is EC type and we have parameters specified
        // then we need to set it accordingly

        if (ecParam != null && ECDSA.equals(privKey.getAlgorithm())) {
            ECParameterSpec ecSpec = new ECParameterSpec(ecParam.getCurve(), ecParam.getG(), ecParam.getN(),
                    ecParam.getH(), ecParam.getSeed());
            KeyFactory keyFactory = KeyFactory.getInstance(ECDSA, BC_PROVIDER);
            ECPrivateKeySpec keySpec = new ECPrivateKeySpec(((BCECPrivateKey) privKey).getS(), ecSpec);
            privKey = (PrivateKey) keyFactory.generatePrivate(keySpec);
        }

        return privKey;

    } catch (PEMException e) {
        LOG.error("loadPrivateKey: Caught PEMException, problem with format of key detected.");
        throw new CryptoException(e);
    } catch (NoSuchProviderException e) {
        LOG.error(
                "loadPrivateKey: Caught NoSuchProviderException, check to make sure the provider is loaded correctly.");
        throw new CryptoException(e);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(
                "loadPrivateKey: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider.");
        throw new CryptoException(e);
    } catch (InvalidKeySpecException e) {
        LOG.error("loadPrivateKey: Caught InvalidKeySpecException, invalid key spec is being used.");
        throw new CryptoException(e);
    } catch (OperatorCreationException e) {
        LOG.error(
                "loadPrivateKey: Caught OperatorCreationException when creating JceOpenSSLPKCS8DecryptorProviderBuilder.");
        throw new CryptoException(e);
    } catch (PKCSException e) {
        LOG.error("loadPrivateKey: Caught PKCSException when decrypting private key.");
        throw new CryptoException(e);
    } catch (IOException e) {
        LOG.error("loadPrivateKey: Caught IOException, while trying to read key.");
        throw new CryptoException(e);
    }
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static PKCS10CertificationRequest getPKCS10CertRequest(String csr) {

    if (csr == null || csr.isEmpty()) {
        LOG.error("getPKCS10CertRequest: CSR is null or empty");
        throw new CryptoException("CSR is null or empty");
    }/*from   ww  w . j a v  a2s.  co  m*/

    try {
        Reader csrReader = new StringReader(csr);
        try (PEMParser pemParser = new PEMParser(csrReader)) {
            Object pemObj = pemParser.readObject();
            if (pemObj instanceof PKCS10CertificationRequest) {
                return (PKCS10CertificationRequest) pemObj;
            }
        }
    } catch (IOException ex) {
        LOG.error("getPKCS10CertRequest: unable to parse csr: " + ex.getMessage());
        throw new CryptoException(ex);
    }

    return null;
}

From source file:craterdog.security.RsaCertificateManager.java

License:Open Source License

@Override
public PrivateKey decodePrivateKey(String pem, char[] password) {
    logger.entry();/* w w  w.  ja  va 2s. c  om*/
    try (StringReader sreader = new StringReader(pem); PemReader preader = new PemReader(sreader)) {
        PEMParser pemParser = new PEMParser(preader);
        PKCS8EncryptedPrivateKeyInfo pinfo = (PKCS8EncryptedPrivateKeyInfo) pemParser.readObject();
        InputDecryptorProvider provider = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(password);
        byte[] keyBytes = pinfo.decryptPrivateKeyInfo(provider).getEncoded();
        KeyFactory factory = KeyFactory.getInstance(ASYMMETRIC_KEY_TYPE, PROVIDER_NAME);
        PrivateKey result = factory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes));
        logger.exit();
        return result;
    } catch (IOException | NoSuchAlgorithmException | NoSuchProviderException | InvalidKeySpecException
            | OperatorCreationException | PKCSException e) {
        RuntimeException exception = new RuntimeException(
                "An unexpected exception occurred while attempting to decode a private key.", e);
        throw logger.throwing(exception);
    }
}