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:nl.codemonkey.tasman.boot2docker.DockerCertificates.java

License:Apache License

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    try {//from   w  ww. java  2 s  .  co  m
        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;
        try (BufferedReader newBufferedReader = Files.newBufferedReader(builder.clientKeyPath,
                Charset.defaultCharset())) {
            clientKeyPair = (PEMKeyPair) new PEMParser(newBufferedReader).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, null);
        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:no.digipost.api.client.util.DigipostPublicKey.java

License:Apache License

public DigipostPublicKey(EncryptionKey encryptionKey) {

    try (Reader sourceReader = new StringReader(encryptionKey.getValue());
            PEMParser pemParser = new PEMParser(sourceReader)) {

        SubjectPublicKeyInfo subjectPublicKeyInfo = (SubjectPublicKeyInfo) pemParser.readObject();
        X509EncodedKeySpec spec = new X509EncodedKeySpec(subjectPublicKeyInfo.getEncoded());
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);

        this.publicKey = publicKey;
        this.publicKeyHash = encryptionKey.getKeyId();

    } catch (Exception e) {
        throw new DigipostClientException(ErrorCode.FAILED_TO_PARSE_ENCRYPTION_KEY,
                "Feil ved parsing av krypteringsnkkel fra Digipost.", e);
    }/*from  w w  w .j a v  a  2 s . c  o  m*/

}

From source file:org.albertschmitt.crypto.RSAService.java

License:Open Source License

/**
 * Read the RSA Private Key from the specified input stream.
 *
 * @param instream//w  ww .  ja va2  s.c  om
 *            The input stream that contains the RSA Private Key.
 * @return The RSAPrivateKey or null if the key is invalid.
 * @throws java.io.IOException
 */
public RSAPrivateKey readPrivateKey(InputStream instream) throws IOException {
    RSAPrivateKey key = null;
    try (InputStreamReader reader = new InputStreamReader(instream)) {
        try (PEMParser pem = new PEMParser(reader)) {
            Object obj = pem.readObject();
            if (obj instanceof PEMKeyPair) {
                PEMKeyPair pkp = (PEMKeyPair) obj;
                PrivateKeyInfo pki = pkp.getPrivateKeyInfo();
                key = new RSAPrivateKey();
                key.setKey(pki);
            }
        }
    }

    return key;
}

From source file:org.albertschmitt.crypto.RSAService.java

License:Open Source License

/**
 * Read the RSA Private Key from the specified input stream using the given password.
 *
 * @param instream/*from  w  w  w  .  j av a  2s. c om*/
 *            The input stream that contains the RSA Private Key.
 * @param password
 *            The password the private key was encrypted with.
 * @return The RSAPrivateKey.
 * @throws IOException
 * @throws OperatorCreationException
 * @throws PKCSException
 */
public RSAPrivateKey readPrivateKey(InputStream instream, char[] password)
        throws IOException, OperatorCreationException, PKCSException {
    RSAPrivateKey key;
    try (InputStreamReader reader = new InputStreamReader(instream)) {
        try (PEMParser pem = new PEMParser(reader)) {
            PKCS8EncryptedPrivateKeyInfo pair = (PKCS8EncryptedPrivateKeyInfo) pem.readObject();
            JceOpenSSLPKCS8DecryptorProviderBuilder jce = new JceOpenSSLPKCS8DecryptorProviderBuilder();
            InputDecryptorProvider decProv = jce.build(password);
            PrivateKeyInfo pki = pair.decryptPrivateKeyInfo(decProv);

            key = new RSAPrivateKey();
            key.setKey(pki);
        }
    }

    return key;
}

From source file:org.albertschmitt.crypto.RSAService.java

License:Open Source License

/**
 * Read the RSA Public Key from the specified input stream.
 *
 * @param instream/*from ww  w .  ja v  a  2 s  .  c  o m*/
 *            The input stream that contains the RSA Public Key.
 * @return The RSAPublicKey.
 * @throws java.io.IOException
 */
public RSAPublicKey readPublicKey(InputStream instream) throws IOException {
    SubjectPublicKeyInfo pki;
    try (InputStreamReader reader = new InputStreamReader(instream)) {
        try (PEMParser pem = new PEMParser(reader)) {
            pki = (SubjectPublicKeyInfo) pem.readObject();
        }
    }

    byte[] data = pki.getEncoded();
    RSAPublicKey key = new RSAPublicKey();
    key.setKey(PublicKeyFactory.createKey(data));

    return key;
}

From source file:org.albertschmitt.crypto.RSAService.java

License:Open Source License

/**
 * Extract the Public Key from the RSA Private Key from the input stream and return it to the client.
 *
 * @param instream/*from w w  w .  j ava2 s  .c  o m*/
 *            The input stream that contains the RSA Private Key.
 * @return The RSAPublicKey.
 * @throws java.io.IOException
 */
public RSAPublicKey readPublicKeyFromPrivate(InputStream instream) throws IOException {
    org.bouncycastle.openssl.PEMKeyPair pkp;
    try (InputStreamReader reader = new InputStreamReader(instream)) {
        try (PEMParser pem = new PEMParser(reader)) {
            pkp = (PEMKeyPair) pem.readObject();
        }
    }
    SubjectPublicKeyInfo pki = pkp.getPublicKeyInfo();
    byte[] data = pki.getEncoded();
    RSAPublicKey key = new RSAPublicKey();
    key.setKey(PublicKeyFactory.createKey(data));

    return key;
}

From source file:org.apache.brooklyn.util.core.crypto.SecureKeys.java

License:Apache License

/** reads RSA or DSA / pem style private key files (viz {@link #toPem(KeyPair)}), extracting also the public key if possible
 * @throws IllegalStateException on errors, in particular {@link PassphraseProblem} if that is the problem */
public static KeyPair readPem(InputStream input, final String passphrase) {
    // TODO cache is only for fallback "reader" strategy (2015-01); delete when Parser confirmed working
    byte[] cache = Streams.readFully(input);
    input = new ByteArrayInputStream(cache);

    try {//from   w  w w . j  ava 2s  . c o  m
        PEMParser pemParser = new PEMParser(new InputStreamReader(input));

        Object object = pemParser.readObject();
        pemParser.close();

        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        KeyPair kp = null;
        if (object == null) {
            throw new IllegalStateException("PEM parsing failed: missing or invalid data");
        } else if (object instanceof PEMEncryptedKeyPair) {
            if (passphrase == null)
                throw new PassphraseProblem("passphrase required");
            try {
                PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder()
                        .build(passphrase.toCharArray());
                kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
            } catch (Exception e) {
                Exceptions.propagateIfFatal(e);
                throw new PassphraseProblem("wrong passphrase", e);
            }
        } else if (object instanceof PEMKeyPair) {
            kp = converter.getKeyPair((PEMKeyPair) object);
        } else if (object instanceof PrivateKeyInfo) {
            PrivateKey privKey = converter.getPrivateKey((PrivateKeyInfo) object);
            kp = new KeyPair(null, privKey);
        } else {
            throw new IllegalStateException("PEM parser support missing for: " + object);
        }

        return kp;

    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);

        // older code relied on PEMReader, now deprecated
        // replaced with above based on http://stackoverflow.com/questions/14919048/bouncy-castle-pemreader-pemparser
        // passes the same tests (Jan 2015) but leaving the old code as a fallback for the time being 

        input = new ByteArrayInputStream(cache);
        try {
            Security.addProvider(new BouncyCastleProvider());
            @SuppressWarnings("deprecation")
            org.bouncycastle.openssl.PEMReader pr = new org.bouncycastle.openssl.PEMReader(
                    new InputStreamReader(input), new PasswordFinder() {
                        public char[] getPassword() {
                            return passphrase != null ? passphrase.toCharArray() : new char[0];
                        }
                    });
            @SuppressWarnings("deprecation")
            KeyPair result = (KeyPair) pr.readObject();
            pr.close();
            if (result == null)
                throw Exceptions.propagate(e);

            log.warn("PEMParser failed when deprecated PEMReader succeeded, with " + result + "; had: " + e);

            return result;

        } catch (Exception e2) {
            Exceptions.propagateIfFatal(e2);
            throw Exceptions.propagate(e);
        }
    }
}

From source file:org.apache.camel.component.ssh.FileKeyPairProvider.java

License:Apache License

public KeyPair[] loadKeys() {
    if (!SecurityUtils.isBouncyCastleRegistered()) {
        throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
    }/*from  www  .  j a v  a  2  s .  co m*/
    List<KeyPair> keys = new ArrayList<KeyPair>();
    for (int i = 0; i < files.length; i++) {
        try {
            PEMParser r = new PEMParser(new InputStreamReader(new FileInputStream(files[i])));
            try {
                Object o = r.readObject();

                JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
                pemConverter.setProvider("BC");
                if (passwordFinder != null && o instanceof PEMEncryptedKeyPair) {
                    JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
                    PEMDecryptorProvider pemDecryptor = decryptorBuilder.build(passwordFinder.getPassword());
                    o = pemConverter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(pemDecryptor));
                }

                if (o instanceof PEMKeyPair) {
                    o = pemConverter.getKeyPair((PEMKeyPair) o);
                    keys.add((KeyPair) o);
                } else if (o instanceof KeyPair) {
                    keys.add((KeyPair) o);
                }

            } finally {
                r.close();
            }
        } catch (Exception e) {
            log.warn("Unable to read key {}: {}", files[i], e);
        }
    }
    return keys.toArray(new KeyPair[keys.size()]);
}

From source file:org.apache.camel.component.ssh.ResourceHelperKeyPairProvider.java

License:Apache License

@Override
protected KeyPair[] loadKeys() {
    if (!SecurityUtils.isBouncyCastleRegistered()) {
        throw new IllegalStateException("BouncyCastle must be registered as a JCE provider");
    }//from  www  .  j  a  v a2s .c o  m

    final List<KeyPair> keys = new ArrayList<KeyPair>(this.resources.length);

    for (String resource : resources) {
        PEMParser r = null;
        InputStreamReader isr = null;
        InputStream is = null;
        try {
            is = ResourceHelper.resolveMandatoryResourceAsInputStream(classResolver, resource);
            isr = new InputStreamReader(is);
            r = new PEMParser(isr);

            Object o = r.readObject();

            JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
            pemConverter.setProvider("BC");
            if (passwordFinder != null && o instanceof PEMEncryptedKeyPair) {
                JcePEMDecryptorProviderBuilder decryptorBuilder = new JcePEMDecryptorProviderBuilder();
                PEMDecryptorProvider pemDecryptor = decryptorBuilder.build(passwordFinder.getPassword());
                o = pemConverter.getKeyPair(((PEMEncryptedKeyPair) o).decryptKeyPair(pemDecryptor));
            }

            if (o instanceof PEMKeyPair) {
                o = pemConverter.getKeyPair((PEMKeyPair) o);
                keys.add((KeyPair) o);
            } else if (o instanceof KeyPair) {
                keys.add((KeyPair) o);
            }

        } catch (Exception e) {
            log.warn("Unable to read key", e);
        } finally {
            IoUtils.closeQuietly(r, is, isr);
        }
    }

    return keys.toArray(new KeyPair[keys.size()]);
}

From source file:org.apache.cloudstack.utils.security.CertUtils.java

License:Apache License

public static X509Certificate pemToX509Certificate(final String pem) throws CertificateException, IOException {
    final PEMParser pemParser = new PEMParser(new StringReader(pem));
    return new JcaX509CertificateConverter().setProvider("BC")
            .getCertificate((X509CertificateHolder) pemParser.readObject());
}