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.liferay.sync.engine.lan.util.LanPEMParserUtil.java

License:Open Source License

public static PrivateKey parsePrivateKey(String privateKey) throws Exception {

    StringBuilder sb = new StringBuilder();

    sb.append("-----BEGIN PRIVATE KEY-----\n");
    sb.append(privateKey);/* ww w  .j  ava 2  s .  c om*/

    if (!privateKey.endsWith("\n")) {
        sb.append("\n");
    }

    sb.append("-----END PRIVATE KEY-----");

    PEMParser pemParser = new PEMParser(new StringReader(sb.toString()));

    JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();

    return jcaPEMKeyConverter.getPrivateKey((PrivateKeyInfo) pemParser.readObject());
}

From source file:com.liferay.sync.engine.lan.util.LanPEMParserUtil.java

License:Open Source License

public static X509Certificate parseX509Certificate(String certificate) throws Exception {

    StringBuilder sb = new StringBuilder();

    sb.append("-----BEGIN CERTIFICATE-----\n");
    sb.append(certificate);//from ww w.j ava  2 s. co  m

    if (!certificate.endsWith("\n")) {
        sb.append("\n");
    }

    sb.append("-----END CERTIFICATE-----");

    PEMParser pemParser = new PEMParser(new StringReader(sb.toString()));

    JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();

    return jcaX509CertificateConverter.getCertificate((X509CertificateHolder) pemParser.readObject());
}

From source file:com.nimbusds.jose.jwk.PEMEncodedKeyParser.java

License:Apache License

/**
 * Parses one or more PEM-encoded certificates, public and / or private
 * keys. The input is assumed to be not password-protected.
 *
 * @param pemEncodedKeys String of one or more PEM-encoded keys.
 *
 * @return The found keys.//from w ww. j ava  2  s.c  o  m
 * 
 * @throws JOSEException If parsing failed.
 */
static List<KeyPair> parseKeys(final String pemEncodedKeys) throws JOSEException {

    // Strips the "---- {BEGIN,END} {CERTIFICATE,PUBLIC/PRIVATE KEY} -----"-like header and footer lines,
    // base64-decodes the body,
    // then uses the proper key specification format to turn it into a JCA Key instance
    final Reader pemReader = new StringReader(pemEncodedKeys);
    final PEMParser parser = new PEMParser(pemReader);
    final List<KeyPair> keys = new ArrayList<>();

    try {
        Object pemObj;
        do {
            pemObj = parser.readObject();

            // if public key, use as-is
            if (pemObj instanceof SubjectPublicKeyInfo) {
                keys.add(toKeyPair((SubjectPublicKeyInfo) pemObj));
                continue;
            }

            // if certificate, use the public key which is signed
            if (pemObj instanceof X509CertificateHolder) {
                keys.add(toKeyPair((X509CertificateHolder) pemObj));
                continue;
            }

            // if EC private key given, it arrives here as a keypair
            if (pemObj instanceof PEMKeyPair) {
                keys.add(toKeyPair((PEMKeyPair) pemObj));
                continue;
            }

            // if (RSA) private key given, return it
            if (pemObj instanceof PrivateKeyInfo) {
                keys.add(toKeyPair((PrivateKeyInfo) pemObj));
                // continue implicitly
            }
        } while (pemObj != null);

        return keys;
    } catch (Exception e) {
        throw new JOSEException(e.getMessage(), e);
    }
}

From source file:com.oath.auth.Utils.java

License:Apache License

/**
 * @param athenzPublicCert the location on the public certificate file
 * @param athenzPrivateKey the location of the private key file
 * @return a KeyStore with loaded key and certificate
 * @throws Exception KeyStore generation can throw Exception for many reasons
 *//*from   w  ww  .j  av a2s  .  c o  m*/
public static KeyStore createKeyStore(final String athenzPublicCert, final String athenzPrivateKey)
        throws Exception {

    X509Certificate certificate;
    PrivateKey privateKey = null;
    KeyStore keyStore = null;
    File certFile = null;
    File keyFile = null;

    try {
        if (Paths.get(athenzPublicCert).isAbsolute() && Paths.get(athenzPrivateKey).isAbsolute()) {
            certFile = new File(athenzPublicCert);
            keyFile = new File(athenzPrivateKey);
            long startTime = System.currentTimeMillis();
            while (!certFile.exists() || !keyFile.exists()) {
                long durationInMillis = System.currentTimeMillis() - startTime;
                if (durationInMillis > KEY_WAIT_TIME_MILLIS) {
                    throw new RuntimeException("Keyfresher waited " + durationInMillis
                            + " ms for valid public or private key files. Giving up.");
                }
                LOG.error("Missing Athenz public certificate or private key files. Waiting {} ms",
                        durationInMillis);
                Thread.sleep(1000);
            }
        } else {
            certFile = new File(Resources.getResource(athenzPublicCert).getFile());
            keyFile = new File(Resources.getResource(athenzPrivateKey).getFile());
        }
    } catch (Throwable t) {
        throw new IllegalArgumentException(t);
    }

    try (InputStream publicCertStream = new FileInputStream(certFile);
            InputStream privateKeyStream = new FileInputStream(keyFile);
            PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) {

        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
        Object key = pemParser.readObject();

        if (key instanceof PEMKeyPair) {
            PrivateKeyInfo pKeyInfo = ((PEMKeyPair) key).getPrivateKeyInfo();
            privateKey = pemConverter.getPrivateKey(pKeyInfo);
        } else if (key instanceof PrivateKeyInfo) {
            privateKey = pemConverter.getPrivateKey((PrivateKeyInfo) key);
        } else {
            throw new IllegalStateException("Unknown object type: " + key.getClass().getName());
        }

        certificate = (X509Certificate) cf.generateCertificate(publicCertStream);
        keyStore = KeyStore.getInstance("JKS");
        String alias = certificate.getSubjectX500Principal().getName();
        keyStore.load(null);
        keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD, new X509Certificate[] { certificate });

    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }

    return keyStore;
}

From source file:com.oth.jasds.crypto.Crypto.java

public byte[] decryptFileKey(String filekey, String privateKey) {
    try {//from w w w  .j  av  a 2  s  .c o m
        BASE64Decoder b64 = new BASE64Decoder();
        ByteArrayInputStream in = new ByteArrayInputStream(privateKey.getBytes());
        PEMParser pemRd = new PEMParser(new InputStreamReader(in));

        PrivateKey prvKey = null;

        Object obj = pemRd.readObject();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        if (obj instanceof PKCS8EncryptedPrivateKeyInfo) {
            PKCS8EncryptedPrivateKeyInfo pkcs8 = (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) obj;
            JceOpenSSLPKCS8DecryptorProviderBuilder jce = new JceOpenSSLPKCS8DecryptorProviderBuilder()
                    .setProvider("BC");
            InputDecryptorProvider decProv = jce.build("Qwer1234!".toCharArray());
            PrivateKeyInfo pkinfo = pkcs8.decryptPrivateKeyInfo(decProv);

            prvKey = converter.getPrivateKey(pkinfo);

        } else {
            throw new Exception("party");
        }

        Cipher rsaCipher = Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING");
        rsaCipher.init(Cipher.DECRYPT_MODE, prvKey,
                new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT));
        //rsaCipher.init(Cipher.DECRYPT_MODE, prvKey);

        byte[] decfk = rsaCipher.doFinal(b64.decodeBuffer(filekey));
        /*
        AsymmetricBlockCipher e = new RSAEngine();
                
        e = new PKCS1Encoding(e);
        AsymmetricKeyParameter prv = (AsymmetricKeyParameter) PrivateKeyFactory.createKey(prvKey.getEncoded());
        e.init(true, prv);
                
        byte[] fk = b64.decodeBuffer(filekey);
        byte[] decfk = e.processBlock(fk, 0, fk.length);
        */
        System.out.println("done");
        return decfk;
    } catch (IOException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidCipherTextException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (OperatorCreationException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (PKCSException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:com.rovemonteux.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * makes RSA private key from PEM string.
 *
 * @param s PEM string that contains the key
 * @return//from  w w  w.j  a  v  a2s .  c  om
 * @see JCERSAPublicKey
 */
public static RSAKeyPair extractRSAKeyPair(final String s) {
    RSAKeyPair rsaKeyPair;
    try {
        // parse
        final PEMParser parser = new PEMParser(new StringReader(s));
        final Object o = parser.readObject();
        parser.close();
        // check types
        if (!(o instanceof PEMKeyPair)) {
            throw new IOException("Encryption.extractRSAKeyPair: no private key found in string '" + s + "'");
        }
        final PEMKeyPair keyPair = (PEMKeyPair) o;
        if (keyPair.getPrivateKeyInfo() == null) {
            throw new IOException(
                    "Encryption.extractRSAKeyPair: no private key found in key pair of string '" + s + "'");
        }
        if (keyPair.getPublicKeyInfo() == null) {
            throw new IOException(
                    "Encryption.extractRSAKeyPair: no public key found in key pair of string '" + s + "'");
        }

        // convert keys and pack them together into a key pair
        final RSAPrivateCrtKey privateKey = new TempJCERSAPrivateCrtKey(keyPair.getPrivateKeyInfo());
        LOG.debug("JCEPrivateKey={}", privateKey);
        final RSAPublicKey publicKey = new TempJCERSAPublicKey(keyPair.getPublicKeyInfo());
        rsaKeyPair = new RSAKeyPair(publicKey, privateKey);

    } catch (final Exception e) {
        LOG.warn("Encryption.extractPrivateRSAKey: Caught exception:" + e.getMessage());
        rsaKeyPair = null;
    }

    return rsaKeyPair;
}

From source file:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

License:Open Source License

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }// ww w  . j a  v a  2s.  co m

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java

License:Open Source License

private SslCertificates(final Builder builder) throws SslCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new SslCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }//w  ww.j  a va  2 s . c om

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}

From source file:com.spotify.docker.client.DockerCertificates.java

License:Apache License

private PrivateKey readPrivateKey(Path file)
        throws IOException, InvalidKeySpecException, NoSuchAlgorithmException, DockerCertificateException {
    try (BufferedReader reader = Files.newBufferedReader(file, Charset.defaultCharset());
            PEMParser pemParser = new PEMParser(reader)) {

        final Object readObject = pemParser.readObject();

        if (readObject instanceof PEMKeyPair) {
            PEMKeyPair clientKeyPair = (PEMKeyPair) readObject;
            return generatePrivateKey(clientKeyPair.getPrivateKeyInfo());
        } else if (readObject instanceof PrivateKeyInfo) {
            return generatePrivateKey((PrivateKeyInfo) readObject);
        }/*www. j  a va2 s.  co m*/

        throw new DockerCertificateException("Can not generate private key from file: " + file.toString());
    }
}

From source file:com.spotify.helios.client.tls.CertificateAndPrivateKey.java

License:Apache License

public static CertificateAndPrivateKey from(final Path certPath, final Path keyPath)
        throws IOException, GeneralSecurityException {
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");

    final Certificate certificate;
    try (final InputStream is = Files.newInputStream(certPath)) {
        certificate = cf.generateCertificate(is);
    }//  w  ww. j  a  v  a 2s .co  m

    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 x509 certificate.");
    }

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

    return new CertificateAndPrivateKey(certificate, kf.generatePrivate(spec));
}