Example usage for java.security.cert X509Certificate getSubjectDN

List of usage examples for java.security.cert X509Certificate getSubjectDN

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectDN.

Prototype

public abstract Principal getSubjectDN();

Source Link

Document

Denigrated, replaced by #getSubjectX500Principal() .

Usage

From source file:se.inera.axel.shs.client.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/* w  ww. j ava  2  s  .  c  o m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("TLSv1");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:com.app.mvc.http.ext.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from ww w  . ja  v  a 2s. co m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (log.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        log.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                log.debug(" Certificate " + (c + 1) + ":");
                                log.debug("  Subject DN: " + cert.getSubjectDN());
                                log.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                log.debug("  Valid from: " + cert.getNotBefore());
                                log.debug("  Valid until: " + cert.getNotAfter());
                                log.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (log.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    log.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        log.debug("  Subject DN: " + cert.getSubjectDN());
                        log.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        log.debug("  Valid from: " + cert.getNotBefore());
                        log.debug("  Valid until: " + cert.getNotAfter());
                        log.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        log.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        log.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        log.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.miloss.fgsms.bueller.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from w  w  w.  j av  a 2 s  . c om*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        // throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        //  throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        // throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        //   throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
    return null;
}

From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java

private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);// ww w.ja va 2 s  . c om

    for (Certificate c : certs) {
        if (!(c instanceof X509Certificate))
            throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");

        X509Certificate xCert = (X509Certificate) c;

        Principal subject = xCert.getSubjectDN();
        Principal issuer = xCert.getIssuerDN();

        anchors.add(new TrustAnchor(xCert, null));
    }

    X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(anchors, target);
        params.setRevocationEnabled(false);
        params.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
        builder.build(params);

    } catch (InvalidAlgorithmParameterException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
        throw new CloudRuntimeException("No provider for certificate validation", e);
    }

}

From source file:org.forgerock.openidm.filter.AuthFilter.java

private AuthData hasClientCert(ServletRequest request) throws AuthException {

    logger.debug("Client certificate authentication request");
    AuthData ad = new AuthData();
    X509Certificate[] certs = getClientCerts(request);

    if (certs != null) {
        Principal existingPrincipal = request instanceof HttpServletRequest
                ? ((HttpServletRequest) request).getUserPrincipal()
                : null;/* w  ww. j a v  a2  s . co  m*/
        logger.debug("Request {} existing Principal {} has {} certificates",
                new Object[] { request, existingPrincipal, certs.length });
        for (X509Certificate cert : certs) {
            logger.debug("Request {} client certificate subject DN: {}", request, cert.getSubjectDN());
        }
    }
    ad.status = (certs != null && certs.length > 0 && certs[0] != null);
    if (ad.status == false) {
        throw new AuthException(ad.username);
    }
    ad.username = certs[0].getSubjectDN().getName();
    ad.userId = ad.username;
    ad.roles.add("openidm-cert");
    logger.debug("Authentication client certificate subject {}", ad.username);
    return ad;
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileC.java

private void extendSignatureTag(Element signatureEl, UnsignedPropertiesType unsigned) throws IOException {

    XAdESSignature signature = new XAdESSignature(signatureEl);
    X509Certificate signingCertificate = signature.getSigningCertificate();
    Date signingTime = signature.getSigningTime();

    ValidationContext ctx = certificateVerifier.validateCertificate(signingCertificate, signingTime,
            new XAdESCertificateSource(signatureEl, false), null, null);

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = xadesObjectFactory
            .createCompleteCertificateRefsType();
    CertIDListType certIdList = xadesObjectFactory.createCertIDListType();
    completeCertificateRefs.setCertRefs(certIdList);
    List<CertIDType> certIds = certIdList.getCert();

    for (int i = 0; i < ctx.getNeededCertificates().size(); i++) {
        X509Certificate certificate = ctx.getNeededCertificates().get(i).getCertificate();
        CertIDType certId = getCertID(certificate, DigestAlgorithm.SHA1);
        LOG.info("Add a reference for Certificate[subjectName=" + certificate.getSubjectDN() + "] : digest="
                + Hex.encodeHexString(certId.getCertDigest().getDigestValue()) + ",issuer="
                + certId.getIssuerSerial().getX509IssuerName() + ",serial="
                + certId.getIssuerSerial().getX509SerialNumber());
        certIds.add(certId);//w  w  w  . ja v  a2  s  .c om
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = xadesObjectFactory.createCompleteRevocationRefsType();

    incorporateCRLRefs(completeRevocationRefs, ctx);
    incorporateOCSPRefs(completeRevocationRefs, ctx);

    /* Remove previous OCSPRefs and CRLRefs tags. */
    Iterator<?> it = unsigned.getUnsignedSignatureProperties()
            .getCounterSignatureOrSignatureTimeStampOrCompleteCertificateRefs().iterator();
    while (it.hasNext()) {
        Object e = it.next();
        if (e instanceof CompleteRevocationRefsType || e instanceof CompleteCertificateRefsType) {
            it.remove();
        } else if (e instanceof JAXBElement) {
            e = ((JAXBElement<?>) e).getValue();
            if (e instanceof CompleteRevocationRefsType || e instanceof CompleteCertificateRefsType) {
                it.remove();
            }
        }
    }

    unsigned.getUnsignedSignatureProperties().getCounterSignatureOrSignatureTimeStampOrCompleteCertificateRefs()
            .add(xadesObjectFactory.createCompleteCertificateRefs(completeCertificateRefs));
    unsigned.getUnsignedSignatureProperties().getCounterSignatureOrSignatureTimeStampOrCompleteCertificateRefs()
            .add(xadesObjectFactory.createCompleteRevocationRefs(completeRevocationRefs));

}

From source file:org.ejbca.core.protocol.cmp.CmpResponseMessage.java

@Override
public boolean create() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException {
    boolean ret = false;
    // Some general stuff, common for all types of messages
    String issuer = null;//from w  ww .j a v  a2s .  c  om
    String subject = null;
    if (cert != null) {
        X509Certificate x509cert = (X509Certificate) cert;
        issuer = x509cert.getIssuerDN().getName();
        subject = x509cert.getSubjectDN().getName();
    } else if ((signCertChain != null) && (signCertChain.size() > 0)) {
        issuer = ((X509Certificate) signCertChain.iterator().next()).getSubjectDN().getName();
        subject = "CN=fooSubject";
    } else {
        issuer = "CN=fooIssuer";
        subject = "CN=fooSubject";
    }

    final GeneralName issuerName = new GeneralName(new X500Name(issuer));
    final GeneralName subjectName = new GeneralName(new X500Name(subject));
    final PKIHeaderBuilder myPKIHeader = CmpMessageHelper.createPKIHeaderBuilder(issuerName, subjectName,
            senderNonce, recipientNonce, transactionId);
    PKIBody myPKIBody = null;
    final PKIMessage myPKIMessage;

    try {
        if (status.equals(ResponseStatus.SUCCESS)) {
            if (cert != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Creating a CertRepMessage 'accepted'");
                }
                PKIStatusInfo myPKIStatusInfo = new PKIStatusInfo(PKIStatus.granted); // 0 = accepted
                ASN1InputStream certASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cert.getEncoded()));
                ASN1InputStream cacertASN1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(cacert.getEncoded()));
                try {
                    try {
                        CMPCertificate cmpcert = CMPCertificate.getInstance(certASN1InputStream.readObject());
                        CertOrEncCert retCert = new CertOrEncCert(cmpcert);
                        CertifiedKeyPair myCertifiedKeyPair = new CertifiedKeyPair(retCert);
                        CertResponse myCertResponse = new CertResponse(new ASN1Integer(requestId),
                                myPKIStatusInfo, myCertifiedKeyPair, null);

                        CertResponse[] certRespos = { myCertResponse };
                        CMPCertificate[] caPubs = {
                                CMPCertificate.getInstance(cacertASN1InputStream.readObject()) };

                        CertRepMessage myCertRepMessage = new CertRepMessage(caPubs, certRespos);

                        int respType = requestType + 1; // 1 = intitialization response, 3 = certification response etc
                        if (log.isDebugEnabled()) {
                            log.debug("Creating response body of type " + respType);
                        }
                        myPKIBody = new PKIBody(respType, myCertRepMessage);
                    } finally {
                        certASN1InputStream.close();
                        cacertASN1InputStream.close();
                    }
                } catch (IOException e) {
                    throw new IllegalStateException("Unexpected IOException caught.", e);
                }
            }
        } else if (status.equals(ResponseStatus.FAILURE)) {
            if (log.isDebugEnabled()) {
                log.debug("Creating a CertRepMessage 'rejected'");
            }
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(ASN1Integer.getInstance(PKIStatus.rejection.toASN1Primitive()));
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo
                    .getInstance(ASN1Sequence.getInstance(new DERSequence(statusInfoV)));
            myPKIBody = CmpMessageHelper.createCertRequestRejectBody(myPKIStatusInfo, requestId, requestType);

        } else {
            if (log.isDebugEnabled()) {
                log.debug("Creating a 'waiting' message?");
            }
            // Not supported, lets create a PKIError failure instead
            // Create a failure message
            ASN1EncodableVector statusInfoV = new ASN1EncodableVector();
            statusInfoV.add(PKIStatus.rejection); // 2 = rejection
            if (failText != null) {
                statusInfoV.add(new PKIFreeText(new DERUTF8String(failText)));
            }
            statusInfoV.add(CmpMessageHelper.getPKIFailureInfo(failInfo.intValue()));
            PKIStatusInfo myPKIStatusInfo = PKIStatusInfo.getInstance(new DERSequence(statusInfoV));

            ErrorMsgContent myErrorContent = new ErrorMsgContent(myPKIStatusInfo);
            myPKIBody = new PKIBody(23, myErrorContent); // 23 = error                
        }

        if ((pbeKeyId != null) && (pbeKey != null) && (pbeDigestAlg != null) && (pbeMacAlg != null)) {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(CMPObjectIdentifiers.passwordBasedMac));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.protectPKIMessageWithPBE(myPKIMessage, pbeKeyId, pbeKey,
                    pbeDigestAlg, pbeMacAlg, pbeIterationCount);
        } else {
            myPKIHeader.setProtectionAlg(new AlgorithmIdentifier(digest));
            PKIHeader header = myPKIHeader.build();
            myPKIMessage = new PKIMessage(header, myPKIBody);
            responseMessage = CmpMessageHelper.signPKIMessage(myPKIMessage, signCertChain, signKey, digest,
                    provider);
        }

        ret = true;

    } catch (CertificateEncodingException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (InvalidKeyException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchProviderException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SecurityException e) {
        log.error("Error creating CertRepMessage: ", e);
    } catch (SignatureException e) {
        log.error("Error creating CertRepMessage: ", e);
    }

    return ret;
}

From source file:no.digipost.api.interceptors.EbmsClientInterceptor.java

@Override
public boolean handleResponse(final MessageContext messageContext) throws WebServiceClientException {
    SoapMessage saajSoapMessage = (SoapMessage) messageContext.getResponse();
    Iterator<SoapHeaderElement> soapHeaderElementIterator = saajSoapMessage.getSoapHeader()
            .examineHeaderElements(MESSAGING_QNAME);
    if (!soapHeaderElementIterator.hasNext()) {
        throw new MessageSenderValidationException("Missing required ebMS SOAP header");
    }//from w  ww.  j  a v a 2  s  . com
    SoapHeaderElement ebmsMessaging = soapHeaderElementIterator.next();
    Messaging messaging = Marshalling.unmarshal(jaxb2Marshaller, ebmsMessaging, Messaging.class);
    EbmsContext context = EbmsContext.from(messageContext);
    List<Error> warnings = new ArrayList<Error>();
    for (SignalMessage message : messaging.getSignalMessages()) {
        for (Error error : message.getErrors()) {
            // Error i ebms-header uten SOAP-fault er warning. Severity failure gir SOAP-fault.
            warnings.add(error);
        }
        if (message.getReceipt() != null) {
            context.receipts.add(message);
        }
    }
    if (warnings.size() > 0) {
        if (warnings.size() > 1) {
            // If this happens in practice, we should log what the warnings are.
            log.warn("Got more than one ebMS warning in response. Using the first, discarding the rest.");
        }

        context.warning = warnings.get(0);
    }

    for (UserMessage userMessage : messaging.getUserMessages()) {
        context.userMessage = userMessage;
    }
    context.processResponse(context, ebmsMessaging, saajSoapMessage);
    if (messageContext.containsProperty(Wss4jInterceptor.INCOMING_CERTIFICATE)) {
        X509Certificate cert = (X509Certificate) messageContext
                .getProperty(Wss4jInterceptor.INCOMING_CERTIFICATE);
        Organisasjonsnummer responder = extractor.from(cert);
        if (!tekniskMottaker.orgnr.equals(responder)) {
            throw new MessageSenderValidationException(
                    format("Unexpected signer in incoming message. Expected: [%s] Extracted: [%s] from %s",
                            tekniskMottaker.orgnr, responder, cert.getSubjectDN().getName()));
        }
    }
    return true;
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.AuthSSLProtocolSocketFactory.java

@SuppressWarnings("rawtypes")
private SSLContext createSSLContext() {
    try {// ww w  . ja  va 2 s . c o m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:org.votingsystem.web.ejb.SignatureBean.java

private CertificateVS checkAuthorityCertDB(X509Certificate x509AuthorityCert)
        throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, ExceptionVS {
    log.info(x509AuthorityCert.getSubjectDN().toString());
    Query query = dao.getEM().createNamedQuery("findCertBySerialNumberAndType")
            .setParameter("type", CertificateVS.Type.CERTIFICATE_AUTHORITY)
            .setParameter("serialNumber", x509AuthorityCert.getSerialNumber().longValue());
    CertificateVS certificateVS = dao.getSingleResult(CertificateVS.class, query);
    if (certificateVS == null) {
        certificateVS = dao.persist(CertificateVS.AUTHORITY(x509AuthorityCert, null));
        log.info("ADDED NEW FILE SYSTEM CA CERT - certificateVS.id:" + certificateVS.getId());
    } else if (CertificateVS.State.OK != certificateVS.getState()) {
        throw new ExceptionVS("File system athority cert: " + x509AuthorityCert.getSubjectDN() + " }' "
                + " - certificateVS.id: " + certificateVS.getId() + " - state:" + certificateVS.getState());
    } else if (certificateVS.getType() != CertificateVS.Type.CERTIFICATE_AUTHORITY) {
        String msg = "Updated from type " + certificateVS.getType() + " to type 'CERTIFICATE_AUTHORITY'";
        certificateVS.setDescription(certificateVS.getDescription() + "###" + msg);
        certificateVS.setType(CertificateVS.Type.CERTIFICATE_AUTHORITY);
        dao.merge(certificateVS);/*from www .  j a v  a2  s  .c  o m*/
    }
    return certificateVS;
}