Example usage for java.security.cert CertificateFactory getInstance

List of usage examples for java.security.cert CertificateFactory getInstance

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory getInstance.

Prototype

public static final CertificateFactory getInstance(String type) throws CertificateException 

Source Link

Document

Returns a certificate factory object that implements the specified certificate type.

Usage

From source file:org.kuali.rice.ksb.security.SignatureVerifyingRequestWrapper.java

public SignatureVerifyingRequestWrapper(HttpServletRequest request) {
    super(request);
    String encodedSignature = request.getHeader(KSBConstants.DIGITAL_SIGNATURE_HEADER);
    if (StringUtils.isEmpty(encodedSignature)) {
        throw new RuntimeException("A digital signature was required on the request but none was found.");
    }/*from  w  w  w.jav  a2  s  .  c  om*/
    String verificationAlias = request.getHeader(KSBConstants.KEYSTORE_ALIAS_HEADER);
    String encodedCertificate = request.getHeader(KSBConstants.KEYSTORE_CERTIFICATE_HEADER);
    if ((StringUtils.isEmpty(verificationAlias)) && (StringUtils.isEmpty(encodedCertificate))) {
        throw new RuntimeException(
                "A verification alias or certificate was required on the request but neither was found.");
    }
    try {
        this.digitalSignature = Base64.decodeBase64(encodedSignature.getBytes("UTF-8"));
        if (StringUtils.isNotBlank(encodedCertificate)) {
            byte[] certificate = Base64.decodeBase64(encodedCertificate.getBytes("UTF-8"));
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            this.signature = KSBServiceLocator.getDigitalSignatureService()
                    .getSignatureForVerification(cf.generateCertificate(new ByteArrayInputStream(certificate)));
        } else if (StringUtils.isNotBlank(verificationAlias)) {
            this.signature = KSBServiceLocator.getDigitalSignatureService()
                    .getSignatureForVerification(verificationAlias);
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to initialize digital signature verification.", e);
    }
}

From source file:org.jasig.cas.adaptors.x509.util.CertUtils.java

/**
 * Gets a certificate factory for creating X.509 artifacts.
 *
 * @return X509 certificate factory./*  ww  w  .jav a2s  .c  om*/
 */
public static CertificateFactory getCertificateFactory() {
    try {
        return CertificateFactory.getInstance(X509_CERTIFICATE_TYPE);
    } catch (final CertificateException e) {
        throw new IllegalStateException("X509 certificate type not supported by default provider.");
    }
}

From source file:be.apsu.extremon.probes.ocsp.OCSPProbe.java

public OCSPProbe() {
    CertificateFactory certificateFactory = null;

    try {//from   w  w  w .ja  v a 2  s  . c  o m
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException cex) {
        log("Don't Have Crypto Libs:" + cex.getMessage());
        System.exit(1);
    }

    try {
        certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("certificate"))));
        trustAnchorCert = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(Base64.decodeBase64(confStr("trustanchor"))));
    } catch (CertificateException cex) {
        log("certificate and trustanchor required in config:" + cex.getMessage());
        System.exit(2);
    }

    this.delay = confInt("delay", DEFAULT_DELAY);

    try {
        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        certs.add(this.certificate);
        this.certificatePath = (CertPath) certificateFactory.generateCertPath(certs);

        TrustAnchor trustAnchor = new TrustAnchor(this.trustAnchorCert, null);
        Set<TrustAnchor> trustedCertsSet = new HashSet<TrustAnchor>();
        trustedCertsSet.add(trustAnchor);

        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        certSet.add(this.trustAnchorCert);
        CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
        CertStore store = CertStore.getInstance("Collection", storeParams);

        pkixParams = new PKIXParameters(trustedCertsSet);
        pkixParams.addCertStore(store);

        Security.setProperty("ocsp.enable", "true");
        Security.setProperty("ocsp.responderURL", confStr("url"));
        Security.setProperty("ocsp.responderCertSubjectName",
                this.trustAnchorCert.getSubjectX500Principal().getName());

        this.certificatePathValidator = CertPathValidator.getInstance("PKIX");
    } catch (InvalidAlgorithmParameterException iaex) {
        log("Invalid Algorithm Parameter:" + iaex.getMessage());
        System.exit(3);
    } catch (CertificateException cex) {
        log("Certificate Exception:" + cex.getMessage());
        System.exit(4);
    } catch (NoSuchAlgorithmException nsaex) {
        log("No Such Algorithm:" + nsaex.getMessage());
        System.exit(5);
    } catch (Exception ex) {
        log(ex.getMessage());
        System.exit(6);
    }

    start();
    log("Initialized");
}

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

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");
    }//from w w w . ja v  a  2 s  .  c o 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 (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}

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

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");
    }//from w  w w.  jav a  2 s  . com

    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.vmware.admiral.auth.lightwave.pc.X509CertificateHelper.java

public X509Certificate getX509CertificateFromBase64(String base64Cert) throws CertificateException {
    byte[] sslTrustBytes = base64Cert.getBytes();
    InputStream is = new ByteArrayInputStream(Base64.decodeBase64(sslTrustBytes));

    CertificateFactory cf = CertificateFactory.getInstance("X509");

    return (X509Certificate) cf.generateCertificate(is);
}

From source file:com.google.u2f.tools.httpserver.U2fHttpServer.java

public U2fHttpServer() {
    ChallengeGenerator challengeGenerator = new ChallengeGenerator() {
        @Override//from   w  w w.j  a v  a 2  s .co  m
        public byte[] generateChallenge(String accountName) {
            try {
                return Hex.decodeHex("1234".toCharArray());
            } catch (DecoderException e) {
                throw new RuntimeException(e);
            }
        }
    };

    SessionIdGenerator sessionIdGenerator = new SessionIdGenerator() {
        @Override
        public String generateSessionId(String accountName) {
            return new StringBuilder().append("sessionId_").append(sessionIdCounter++).append("_")
                    .append(accountName).toString();
        }
    };

    X509Certificate trustedCertificate;
    try {
        trustedCertificate = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(new ByteArrayInputStream(
                        Hex.decodeHex(("308201433081eaa0030201020209012333009941964658300a06082a8648ce3d"
                                + "040302301b3119301706035504031310476e756262792048534d2043412030"
                                + "303022180f32303132303630313030303030305a180f323036323035333132"
                                + "33353935395a30303119301706035504031310476f6f676c6520476e756262"
                                + "7920763031133011060355042d030a00012333009941964658305930130607"
                                + "2a8648ce3d020106082a8648ce3d03010703420004aabc1b97a7c391f8b1fe"
                                + "5280a65cf27890409bdc392e181ff00ccf39599461d583f3351b21602cf99e"
                                + "2fe71e7f838658b42df49f06b8446d375d2aaaa8e317a1300a06082a8648ce"
                                + "3d0403020348003045022037788207c2239373b289169cfd3500b54fe92903"
                                + "e6772ea995cd2ce4a670fba5022100dfbfe7da528600be0d6125060d029f40"
                                + "c647bc053e35226fffb66cd7f4609b49").toCharArray())));
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    } catch (DecoderException e) {
        throw new RuntimeException(e);
    }
    DataStore dataStore = new MemoryDataStore(sessionIdGenerator);
    dataStore.addTrustedCertificate(trustedCertificate);

    // this implementation will only accept signatures from http://localhost:8080
    u2fServer = new U2FServerReferenceImpl(challengeGenerator, dataStore, new BouncyCastleCrypto(),
            ImmutableSet.of("http://localhost:8080"));
    Container dispatchContainer = new RequestDispatcher()
            .registerContainer("/", new StaticHandler("text/html", "html/index.html"))
            .registerContainer("/enroll", new StaticHandler("text/html", "html/enroll.html"))
            .registerContainer("/enrollData.js", new EnrollDataServlet(u2fServer))
            .registerContainer("/enrollFinish", new EnrollFinishServlet(u2fServer))
            .registerContainer("/sign", new StaticHandler("text/html", "html/sign.html"))
            .registerContainer("/signData.js", new SignDataServlet(u2fServer))
            .registerContainer("/signFinish", new SignFinishServlet(u2fServer));

    try {
        Connection connection = new SocketConnection(new ContainerServer(dispatchContainer));

        try {
            connection.connect(new InetSocketAddress("0.0.0.0", 8080));

            synchronized (lock) {
                lock.wait();
            }
        } finally {
            connection.close();
        }
    } catch (IOException e) {
        Log.severe("Error with HTTP server: " + e);
        return;
    } catch (InterruptedException e) {
        Log.info("Interrupted");
        return;
    }
}

From source file:org.comixwall.pffw.Utils.java

/**
 * Create an SSL context which trusts the PFFW server certificate.
 * PFFW server certificate is self signed, hence is not verified by the default SSL context.
 *
 * @param owner Fragment which initiated the call to this method.
 * @return SSL context.//from  w  w w.  j a v  a  2 s .  com
 */
static SSLContext getSslContext(final Fragment owner) {
    SSLContext sslContext = null;
    try {
        // Load our crt from an InputStream
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream crtInput = owner.getResources().openRawResource(
                owner.getResources().getIdentifier("server", "raw", owner.getActivity().getPackageName()));

        Certificate crt;
        try {
            crt = cf.generateCertificate(crtInput);
            logger.finest("server.crt=" + ((X509Certificate) crt).getSubjectDN());
        } finally {
            crtInput.close();
        }

        // Create a KeyStore containing our trusted crt
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("server.crt", crt);

        // Create a TrustManager that trusts the crt in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Create an SSLContext that uses our TrustManager
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

    } catch (Exception e) {
        e.printStackTrace();
        logger.severe("getSslContext exception: " + e.toString());
    }
    return sslContext;
}

From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java

/**
 * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the
 * store with the password using {@link KeyStore#load(InputStream,
 * char[])} method./*  w ww  .j  av  a  2 s  . com*/
 *
 * @param store The key store holding the certificate details
 * @param alias The alias of the certificate to use
 */
public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(store);

    // Loading the CA certificate from store.
    final Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    AsyncHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Embedded SSL certificate has expired.");
    }

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid.");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid.");
            } else {
                Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates.");
                try {
                    for (X509Certificate cert : chain) {
                        Log.i(LOG_TAG, "Server Certificate Details:");
                        Log.i(LOG_TAG, "---------------------------");
                        Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                        Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                        Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                        Log.i(LOG_TAG, "Version: " + cert.getVersion());
                        Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                        Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                        Log.i(LOG_TAG, "---------------------------");

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's public key chain.
                        cert.verify(rootca.getPublicKey());
                    }
                } catch (InvalidKeyException e) {
                    error = e;
                } catch (NoSuchAlgorithmException e) {
                    error = e;
                } catch (NoSuchProviderException e) {
                    error = e;
                } catch (SignatureException e) {
                    error = e;
                }
            }
            if (null != error) {
                Log.e(LOG_TAG, "Certificate error", error);
                throw new CertificateException(error);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return acceptedIssuers;
        }
    } }, null);

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:com.vmware.identity.samlservice.SamlServiceTest.java

@BeforeClass
public static void setUp() throws Exception {
    SharedUtils.bootstrap(false); // use real data
    String tenantName = ServerConfig.getTenant(0);
    String rpName = ServerConfig.getRelyingParty(tenantName, 0);
    String issuerUrl = ServerConfig.getRelyingPartyUrl(rpName);
    String acsName = ServerConfig.getAssertionConsumerService(rpName, 0);
    acsUrl = ServerConfig.getServiceEndpoint(acsName);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(SamlServiceTest.class.getResource("/sts-store.jks").getFile());
    char[] stsKeystorePassword = "ca$hc0w".toCharArray();
    ks.load(is, stsKeystorePassword);// w  ww . j  a  v  a  2 s .c om

    String stsAlias = "stskey";
    Certificate certificate = ks.getCertificate(stsAlias);
    Key key = ks.getKey(stsAlias, stsKeystorePassword);

    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    certificates.add((X509Certificate) certificate);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certFactory.generateCertPath(certificates);

    privateKey = (PrivateKey) key;
    x509Certificate = (X509Certificate) certificate;

    SamlServiceFactory factory = new DefaultSamlServiceFactory();
    service = factory.createSamlService(privateKey, SignatureAlgorithm.RSA_SHA256,
            SignatureAlgorithm.RSA_SHA256, issuerUrl, certPath);
}