Search in sources :

Example 1 with PEMParser

use of org.bouncycastle.openssl.PEMParser in project cas by apereo.

the class PrivateKeyFactoryBean method readPemPrivateKey.

private PrivateKey readPemPrivateKey() throws Exception {
    LOGGER.debug("Attempting to read [{}] as PEM", this.location.getFile());
    try (BufferedReader br = new BufferedReader(new FileReader(this.location.getFile()))) {
        final PEMParser pp = new PEMParser(br);
        final PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
        final KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
        return kp.getPrivate();
    } catch (final Exception e) {
        LOGGER.debug(e.getMessage(), e);
        return null;
    }
}
Also used : KeyPair(java.security.KeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) PEMParser(org.bouncycastle.openssl.PEMParser) BufferedReader(java.io.BufferedReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) FileReader(java.io.FileReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair)

Example 2 with PEMParser

use of org.bouncycastle.openssl.PEMParser 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 3 with PEMParser

use of org.bouncycastle.openssl.PEMParser in project oxAuth by GluuFederation.

the class JwtUtil method getPublicKey.

public static PublicKey getPublicKey(String jwksUri, String jwks, SignatureAlgorithm signatureAlgorithm, String keyId) {
    log.debug("Retrieving JWK...");
    JSONObject jsonKeyValue = getJsonKey(jwksUri, jwks, keyId);
    if (jsonKeyValue == null) {
        return null;
    }
    org.xdi.oxauth.model.crypto.PublicKey publicKey = null;
    try {
        String resultKeyId = jsonKeyValue.getString(KEY_ID);
        if (signatureAlgorithm == null) {
            signatureAlgorithm = SignatureAlgorithm.fromString(jsonKeyValue.getString(ALGORITHM));
            if (signatureAlgorithm == null) {
                log.error(String.format("Failed to determine key '%s' signature algorithm", resultKeyId));
                return null;
            }
        }
        JSONObject jsonPublicKey = jsonKeyValue;
        if (jsonKeyValue.has(PUBLIC_KEY)) {
            // Use internal jwks.json format
            jsonPublicKey = jsonKeyValue.getJSONObject(PUBLIC_KEY);
        }
        if (signatureAlgorithm == SignatureAlgorithm.RS256 || signatureAlgorithm == SignatureAlgorithm.RS384 || signatureAlgorithm == SignatureAlgorithm.RS512) {
            //String alg = jsonKeyValue.getString(ALGORITHM);
            //String use = jsonKeyValue.getString(KEY_USE);
            String exp = jsonPublicKey.getString(EXPONENT);
            String mod = jsonPublicKey.getString(MODULUS);
            BigInteger publicExponent = new BigInteger(1, Base64Util.base64urldecode(exp));
            BigInteger modulus = new BigInteger(1, Base64Util.base64urldecode(mod));
            publicKey = new RSAPublicKey(modulus, publicExponent);
        } else if (signatureAlgorithm == SignatureAlgorithm.ES256 || signatureAlgorithm == SignatureAlgorithm.ES384 || signatureAlgorithm == SignatureAlgorithm.ES512) {
            //String alg = jsonKeyValue.getString(ALGORITHM);
            //String use = jsonKeyValue.getString(KEY_USE);
            //String crv = jsonKeyValue.getString(CURVE);
            String xx = jsonPublicKey.getString(X);
            String yy = jsonPublicKey.getString(Y);
            BigInteger x = new BigInteger(1, Base64Util.base64urldecode(xx));
            BigInteger y = new BigInteger(1, Base64Util.base64urldecode(yy));
            publicKey = new ECDSAPublicKey(signatureAlgorithm, x, y);
        }
        if (publicKey != null && jsonKeyValue.has(CERTIFICATE_CHAIN)) {
            final String BEGIN = "-----BEGIN CERTIFICATE-----";
            final String END = "-----END CERTIFICATE-----";
            JSONArray certChain = jsonKeyValue.getJSONArray(CERTIFICATE_CHAIN);
            String certificateString = BEGIN + "\n" + certChain.getString(0) + "\n" + END;
            StringReader sr = new StringReader(certificateString);
            PEMParser pemReader = new PEMParser(sr);
            X509Certificate cert = (X509CertificateObject) pemReader.readObject();
            Certificate certificate = new Certificate(signatureAlgorithm, cert);
            publicKey.setCertificate(certificate);
        }
        if (publicKey != null) {
            publicKey.setKeyId(resultKeyId);
            publicKey.setSignatureAlgorithm(signatureAlgorithm);
        }
    } catch (Exception ex) {
        log.error(ex.getMessage(), ex);
    }
    return publicKey;
}
Also used : JSONArray(org.codehaus.jettison.json.JSONArray) PublicKey(org.xdi.oxauth.model.crypto.PublicKey) X509Certificate(java.security.cert.X509Certificate) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONObject(org.codehaus.jettison.json.JSONObject) RSAPublicKey(org.xdi.oxauth.model.crypto.signature.RSAPublicKey) PEMParser(org.bouncycastle.openssl.PEMParser) X509CertificateObject(org.bouncycastle.jce.provider.X509CertificateObject) StringReader(java.io.StringReader) BigInteger(java.math.BigInteger) ECDSAPublicKey(org.xdi.oxauth.model.crypto.signature.ECDSAPublicKey) X509Certificate(java.security.cert.X509Certificate) Certificate(org.xdi.oxauth.model.crypto.Certificate)

Example 4 with PEMParser

use of org.bouncycastle.openssl.PEMParser in project oxTrust by GluuFederation.

the class SSLService method getPEMCertificateStatic.

/**
     * Extracts X509 certificate from pem-encoded stream.
     * 
     * @param certStream
     * @return
     */
public static X509Certificate getPEMCertificateStatic(InputStream certStream) throws IOException {
    X509Certificate cert = null;
    Reader reader = null;
    PEMParser r = null;
    try {
        reader = new InputStreamReader(certStream);
        r = new PEMParser(reader);
        cert = (X509Certificate) r.readObject();
    } finally {
        IOUtils.closeQuietly(r);
        IOUtils.closeQuietly(reader);
    }
    return cert;
}
Also used : PEMParser(org.bouncycastle.openssl.PEMParser) InputStreamReader(java.io.InputStreamReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) X509Certificate(java.security.cert.X509Certificate)

Example 5 with PEMParser

use of org.bouncycastle.openssl.PEMParser in project ddf by codice.

the class KeystoreEditor method addToStore.

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;
    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();
}
Also used : OriginatorInfo(org.bouncycastle.asn1.cms.OriginatorInfo) PrivateKey(java.security.PrivateKey) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) JcaPEMKeyConverter(org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter) X500Name(org.bouncycastle.asn1.x500.X500Name) JcePEMDecryptorProviderBuilder(org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder) CertificateFactory(java.security.cert.CertificateFactory) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) PEMParser(org.bouncycastle.openssl.PEMParser) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) RDN(org.bouncycastle.asn1.x500.RDN) Path(java.nio.file.Path) PKCS8Key(org.apache.commons.ssl.PKCS8Key) CMSEnvelopedData(org.bouncycastle.cms.CMSEnvelopedData) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) KeyPair(java.security.KeyPair) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) Enumeration(java.util.Enumeration) InputStreamReader(java.io.InputStreamReader) SignedData(org.bouncycastle.asn1.cms.SignedData) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) PKCS8EncryptedPrivateKeyInfo(org.bouncycastle.pkcs.PKCS8EncryptedPrivateKeyInfo) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) InstanceAlreadyExistsException(javax.management.InstanceAlreadyExistsException) KeyManagementException(java.security.KeyManagementException) MalformedObjectNameException(javax.management.MalformedObjectNameException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) PEMEncryptedKeyPair(org.bouncycastle.openssl.PEMEncryptedKeyPair) ASN1Set(org.bouncycastle.asn1.ASN1Set) ByteArrayInputStream(java.io.ByteArrayInputStream) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) BufferedReader(java.io.BufferedReader) PEMKeyPair(org.bouncycastle.openssl.PEMKeyPair) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) Key(java.security.Key) PrivateKey(java.security.PrivateKey) PKCS8Key(org.apache.commons.ssl.PKCS8Key) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

PEMParser (org.bouncycastle.openssl.PEMParser)12 PEMKeyPair (org.bouncycastle.openssl.PEMKeyPair)8 KeyPair (java.security.KeyPair)7 InputStreamReader (java.io.InputStreamReader)6 JcaPEMKeyConverter (org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter)6 BufferedReader (java.io.BufferedReader)4 IOException (java.io.IOException)4 Reader (java.io.Reader)4 X509Certificate (java.security.cert.X509Certificate)4 PEMDecryptorProvider (org.bouncycastle.openssl.PEMDecryptorProvider)4 PEMEncryptedKeyPair (org.bouncycastle.openssl.PEMEncryptedKeyPair)4 JcePEMDecryptorProviderBuilder (org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder)4 InputStream (java.io.InputStream)3 KeyFactory (java.security.KeyFactory)3 FileReader (java.io.FileReader)2 StringReader (java.io.StringReader)2 BigInteger (java.math.BigInteger)2 GeneralSecurityException (java.security.GeneralSecurityException)2 Certificate (java.security.cert.Certificate)2 CertificateException (java.security.cert.CertificateException)2