Search in sources :

Example 1 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project helios by spotify.

the class CertificateAndPrivateKey method from.

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);
    }
    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));
}
Also used : PEMParser(org.bouncycastle.openssl.PEMParser) InputStream(java.io.InputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) BufferedReader(java.io.BufferedReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) CertificateFactory(java.security.cert.CertificateFactory) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) KeyFactory(java.security.KeyFactory) Certificate(java.security.cert.Certificate)

Example 2 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project athenz by yahoo.

the class Utils method createKeyStore.

/**
 * @param athensPublicKey the location on the public key file
 * @param athensPrivateKey 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
 */
public static KeyStore createKeyStore(final String athensPublicKey, final String athensPrivateKey) throws Exception {
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    final JcaPEMKeyConverter pemConverter = new JcaPEMKeyConverter();
    X509Certificate certificate;
    PrivateKey privateKey = null;
    final InputStream publicCertStream;
    final InputStream privateKeyStream;
    try {
        if (Paths.get(athensPublicKey).isAbsolute() && Paths.get(athensPrivateKey).isAbsolute()) {
            // Can not cover this branch in unit test. Can not refer any files by absolute paths
            File certFile = new File(athensPublicKey);
            File keyFile = new File(athensPrivateKey);
            while (!certFile.exists() || !keyFile.exists()) {
                LOG.error("Missing Athenz public or private key files");
                Thread.sleep(1000);
            }
            publicCertStream = new FileInputStream(athensPublicKey);
            privateKeyStream = new FileInputStream(athensPrivateKey);
        } else {
            publicCertStream = Resources.getResource(athensPublicKey).openStream();
            privateKeyStream = Resources.getResource(athensPrivateKey).openStream();
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
    try (PEMParser pemParser = new PEMParser(new InputStreamReader(privateKeyStream))) {
        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());
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unable to parse private key", e);
    }
    certificate = (X509Certificate) cf.generateCertificate(publicCertStream);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    String alias = certificate.getSubjectX500Principal().getName();
    keyStore.load(null);
    keyStore.setKeyEntry(alias, privateKey, KEYSTORE_PASSWORD.toCharArray(), new X509Certificate[] { certificate });
    return keyStore;
}
Also used : PrivateKey(java.security.PrivateKey) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) PEMParser(org.bouncycastle.openssl.PEMParser) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) File(java.io.File) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo)

Example 3 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project keystore-explorer by kaikramer.

the class OpenSslPvkUtilTest method checkCompatibilityWithBC.

@ParameterizedTest
@MethodSource("privateKeys")
public void checkCompatibilityWithBC(PrivateKey privateKey) throws Exception {
    String key = OpenSslPvkUtil.getPem(privateKey);
    try (PEMParser pemParser = new PEMParser(new StringReader(key))) {
        Object obj = pemParser.readObject();
        assertThat(obj).isInstanceOf(PEMKeyPair.class);
        KeyPair keyPair = new JcaPEMKeyConverter().getKeyPair((PEMKeyPair) obj);
        assertThat(keyPair.getPrivate()).isEqualTo(privateKey);
    }
}
Also used : KeyPair(java.security.KeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) StringReader(java.io.StringReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 4 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project photon-model by vmware.

the class CertificateUtil method createKeyPair.

/**
 * Utility method to decode a PEM encoded private key string to a PrivateKey instance
 * @param key
 *         - 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);
    }
}
Also used : PEMParser(org.bouncycastle.openssl.PEMParser) StringReader(java.io.StringReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) DEROctetString(org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException)

Example 5 with PEMKeyPair

use of org.bouncycastle.openssl.PEMKeyPair in project runwar by cfmlprojects.

the class SSLUtil method loadPemPrivateKey.

private static PrivateKey loadPemPrivateKey(final File file, final char[] passphrase) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    final PEMParser pemParser = new PEMParser(new BufferedReader(new FileReader(file)));
    final PEMDecryptorProvider build = new JcePEMDecryptorProviderBuilder().build(passphrase);
    final JcaPEMKeyConverter jcaPEMKeyConverter = new JcaPEMKeyConverter();
    PrivateKey privateKey;
    try {
        final Object object = pemParser.readObject();
        if (object instanceof PEMEncryptedKeyPair) {
            privateKey = jcaPEMKeyConverter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(build)).getPrivate();
        } else {
            PrivateKeyInfo privateKeyInfo;
            if (object instanceof PEMKeyPair) {
                privateKeyInfo = ((PEMKeyPair) object).getPrivateKeyInfo();
            } else {
                privateKeyInfo = (PrivateKeyInfo) object;
            }
            if (privateKeyInfo != null) {
                privateKey = new JcaPEMKeyConverter().getPrivateKey(privateKeyInfo);
            } else {
                final KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC");
                final FileInputStream fileInputStream = new FileInputStream(file);
                keyStore.load(fileInputStream, passphrase);
                fileInputStream.close();
                final Enumeration<String> aliases = keyStore.aliases();
                String alias = "";
                while (aliases.hasMoreElements()) {
                    alias = aliases.nextElement();
                }
                privateKey = (PrivateKey) keyStore.getKey(alias, passphrase);
            }
        }
    } finally {
        pemParser.close();
    }
    pemParser.close();
    return privateKey;
}
Also used : PrivateKey(java.security.PrivateKey) PEMDecryptorProvider(org.bouncycastle.openssl.PEMDecryptorProvider) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) BufferedReader(java.io.BufferedReader) FileReader(java.io.FileReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Aggregations

PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)37 PEMParser (org.bouncycastle.openssl.PEMParser)35 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)28 PrivateKeyInfo (org.bouncycastle.asn1.pkcs.PrivateKeyInfo)17 IOException (java.io.IOException)13 InputStreamReader (java.io.InputStreamReader)13 PrivateKey (java.security.PrivateKey)12 PEMEncryptedKeyPair (org.bouncycastle.openssl.PEMEncryptedKeyPair)12 StringReader (java.io.StringReader)11 PEMDecryptorProvider (org.bouncycastle.openssl.PEMDecryptorProvider)11 JcePEMDecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder)11 InputStream (java.io.InputStream)10 KeyPair (java.security.KeyPair)8 Reader (java.io.Reader)7 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)7 PKCS8EncryptedPrivateKeyInfo (org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo)7 JceOpenSSLPKCS8DecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JceOpenSSLPKCS8DecryptorProviderBuilder)6 InputDecryptorProvider (org.bouncycastle.operator.InputDecryptorProvider)6 PemObject (org.bouncycastle.util.io.pem.PemObject)6 KeyFactory (java.security.KeyFactory)5