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:eu.europa.esig.dss.x509.KeyStoreCertificateSource.java

public List<CertificateToken> populate() {
    List<CertificateToken> list = new ArrayList<CertificateToken>();
    try {/*  w  w  w. j a v  a 2  s.  co  m*/
        KeyStore keyStore = getKeyStore();
        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            final Certificate certificate = keyStore.getCertificate(alias);
            if (certificate != null) {
                X509Certificate x509Certificate = (X509Certificate) certificate;
                logger.debug("Alias " + alias + " Cert " + x509Certificate.getSubjectDN());

                CertificateToken certToken = certPool.getInstance(new CertificateToken(x509Certificate),
                        CertificateSourceType.OTHER);
                list.add(certToken);
            }
            Certificate[] certificateChain = keyStore.getCertificateChain(alias);
            if (certificateChain != null) {
                for (Certificate chainCert : certificateChain) {
                    logger.debug("Alias " + alias + " Cert " + ((X509Certificate) chainCert).getSubjectDN());
                    CertificateToken certToken = certPool.getInstance(
                            new CertificateToken((X509Certificate) chainCert),
                            CertificateSourceType.OCSP_RESPONSE);
                    if (!list.contains(certToken)) {
                        list.add(certToken);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new DSSEncodingException(MSG.CERTIFICATE_CANNOT_BE_READ, e);
    }
    return list;
}

From source file:ee.sk.hwcrypto.demo.controller.SigningController.java

@RequestMapping(value = "/identify", method = RequestMethod.POST)
public Digest identifyUser(@RequestParam String certificate) {
    Digest digest = new Digest();
    try {//  w  w  w. j av  a  2s  .co  m
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        byte[] bytes = Base64.decode(certificate);
        InputStream stream = new ByteArrayInputStream(bytes);
        X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
        cert.checkValidity();
        digest.setHex(cert.getSubjectDN().getName());
        digest.setResult(Result.OK);
        //TODO create session for user cert.getSubjectDN().getName()
        return digest;
    } catch (Exception e) {
        log.error("Error identify ", e);
        digest.setResult(Result.ERROR);
    }
    return digest;
}

From source file:com.cordys.coe.util.cgc.ssl.AuthSSLX509TrustManager.java

/**
 * This method checks if the certificate can be trusted. If you do not want to accept the
 * certificate you need to throw an exception.
 *
 * @param   certificates  The certificates to check.
 * @param   sAuthType     The authentication type.
 *
 * @throws  CertificateException  In case the certificate should not be accepted.
 *//*  w w  w  . j ava  2s  . com*/
public void checkClientTrusted(X509Certificate[] certificates, String sAuthType) throws CertificateException {
    if (m_xtmDefault != null) {
        if (certificates != null) {
            for (int c = 0; c < certificates.length; c++) {
                X509Certificate cert = certificates[c];

                if (LOG.isInfoEnabled()) {
                    LOG.info(" Client certificate " + (c + 1) + ":");
                    LOG.info("  Subject DN: " + cert.getSubjectDN());
                    LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.info("  Valid from: " + cert.getNotBefore());
                    LOG.info("  Valid until: " + cert.getNotAfter());
                    LOG.info("  Issuer: " + cert.getIssuerDN());
                }

                try {
                    cert.checkValidity();
                } catch (CertificateExpiredException e) {
                    LOG.fatal("Client certificate " + cert.getSubjectDN() + " is expired.");
                } catch (CertificateNotYetValidException e) {
                    LOG.fatal("Client certificate " + cert.getSubjectDN() + " is not yet valid.");
                }
            }
        }

        // Call the super to do the actual checking.
        m_xtmDefault.checkClientTrusted(certificates, sAuthType);
    }
}

From source file:com.cordys.coe.util.cgc.ssl.AuthSSLX509TrustManager.java

/**
 * This method checks if the server certificate is trusted.
 *
 * @param   certificates  The list of certificates.
 * @param   sAuthType     The authentication type.
 *
 * @throws  CertificateException  DOCUMENTME
 */// w w  w . j ava 2  s. c  om
public void checkServerTrusted(X509Certificate[] certificates, String sAuthType) throws CertificateException {
    if (m_xtmDefault != null) {
        if (certificates != null) {
            for (int c = 0; c < certificates.length; c++) {
                X509Certificate cert = certificates[c];

                if (LOG.isInfoEnabled()) {
                    LOG.info(" Server certificate " + (c + 1) + ":");
                    LOG.info("  Subject DN: " + cert.getSubjectDN());
                    LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.info("  Valid from: " + cert.getNotBefore());
                    LOG.info("  Valid until: " + cert.getNotAfter());
                    LOG.info("  Issuer: " + cert.getIssuerDN());
                }

                try {
                    cert.checkValidity();
                } catch (CertificateExpiredException e) {
                    LOG.fatal("Server certificate " + cert.getSubjectDN() + " is expired.");
                } catch (CertificateNotYetValidException e) {
                    LOG.fatal("Server certificate " + cert.getSubjectDN() + " is not yet valid.");
                }
            }
        }

        // Call the super to do the actual checking.
        m_xtmDefault.checkServerTrusted(certificates, sAuthType);
    }
}

From source file:org.glite.slcs.httpclient.ssl.ExtendedX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String
 *      authType)/*from  w ww  .j  a  va2s  .  co m*/
 */
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Certificate chain:");
        if (chain != null) {
            for (int i = 0; i < chain.length; i++) {
                X509Certificate certificate = chain[i];
                LOG.debug(i + ": S: " + certificate.getSubjectDN());
                LOG.debug(i + ": I: " + certificate.getIssuerDN());
            }
        }
    }
    try {
        // delegate to default JSSE TrustManager
        defaultTrustManager_.checkServerTrusted(chain, authType);
    } catch (CertificateException ce) {
        LOG.debug("Extended checking of certificate chain");
        // Start with the root and see if the subject or the issuer is
        // in the trustedIssuers HashTable.
        // The root is at the end of the chain.
        boolean trusted = false;
        for (int i = chain.length - 1; i >= 0; i--) {
            X509Certificate cert = chain[i];

            if (isCertificateIssuerTrusted(cert)) {
                LOG.debug("Trusted X509 Issuer: " + cert.getIssuerDN());
                trusted = true;
                break;
            } else if (isCertificateTrusted(cert)) {
                LOG.debug("Trusted X509 Certificate: " + cert.getSubjectDN());
                trusted = true;
                break;
            }
        }

        if (!trusted) {
            LOG.error("No suitable trusted certificate found in truststore: ", ce);
            throw ce;
        }

    }
}

From source file:org.keysupport.shibboleth.idp.x509.X509AuthServlet.java

/** {@inheritDoc} */
@Override/*from w  w w.  j  av  a 2s  .  co  m*/
protected void service(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse)
        throws ServletException, IOException {

    try {
        final String key = ExternalAuthentication.startExternalAuthentication(httpRequest);

        final X509Certificate[] certs = (X509Certificate[]) httpRequest
                .getAttribute("javax.servlet.request.X509Certificate");
        log.debug("{} X.509 Certificate(s) found in request", certs != null ? certs.length : 0);

        if (certs == null || certs.length < 1) {
            log.error("No X.509 Certificates found in request");
            httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                    AuthnEventIds.NO_CREDENTIALS);
            ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
            return;
        }

        final X509Certificate cert = certs[0];
        log.debug("End-entity X.509 certificate found with subject '{}', issued by '{}'",
                cert.getSubjectDN().getName(), cert.getIssuerDN().getName());

        if (trustEngine != null) {
            try {
                final BasicX509Credential cred = new BasicX509Credential(cert);
                cred.setEntityCertificateChain(Arrays.asList(certs));
                if (trustEngine.validate(cred, new CriteriaSet())) {
                    log.debug("Trust engine validated X.509 certificate");
                } else {
                    log.warn("Trust engine failed to validate X.509 certificate");
                    httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_ERROR_KEY,
                            AuthnEventIds.INVALID_CREDENTIALS);
                    ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                    return;
                }
            } catch (final SecurityException e) {
                log.error("Exception raised by trust engine", e);
                httpRequest.setAttribute(ExternalAuthentication.AUTHENTICATION_EXCEPTION_KEY, e);
                ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);
                return;
            }
        }

        final String passthrough = httpRequest.getParameter(PASSTHROUGH_PARAM);
        if (passthrough != null && Boolean.parseBoolean(passthrough)) {
            log.debug("Setting UI passthrough cookie");
            final Cookie cookie = new Cookie(PASSTHROUGH_PARAM, "1");
            cookie.setPath(httpRequest.getContextPath());
            cookie.setMaxAge(60 * 60 * 24 * 365);
            cookie.setSecure(true);
            httpResponse.addCookie(cookie);
        }

        final Subject subject = new Subject();
        subject.getPublicCredentials().add(cert);
        subject.getPrincipals().add(cert.getSubjectX500Principal());

        httpRequest.setAttribute(ExternalAuthentication.SUBJECT_KEY, subject);

        //         final String revokeConsent = httpRequest
        //               .getParameter(ProfileInterceptorFlowDescriptor.REVOKE_CONSENT_PARAM);
        //         if (revokeConsent != null
        //               && ("1".equals(revokeConsent) || "true"
        //                     .equals(revokeConsent))) {
        //            httpRequest.setAttribute(
        //                  ExternalAuthentication.REVOKECONSENT_KEY, Boolean.TRUE);
        //         }

        ExternalAuthentication.finishExternalAuthentication(key, httpRequest, httpResponse);

    } catch (final ExternalAuthenticationException e) {
        throw new ServletException("Error processing external authentication request", e);
    }
}

From source file:org.brekka.pegasus.core.services.impl.CertificateAuthenticationServiceImpl.java

@Override
@Transactional()//  w  w w . j  ava  2 s .  c  o  m
public DigitalCertificate authenticate(X509Certificate certificate)
        throws BadCredentialsException, DisabledException {
    byte[] signature = certificate.getSignature();
    String subjectDN = certificate.getSubjectDN().getName();
    String commonName = null;

    Matcher matcher = matchAllowedSubjectDN(subjectDN, allowedSubjectDistinguishedNamePatterns);
    if (matcher.groupCount() > 0) {
        commonName = matcher.group(1);
    }

    byte[] subjectDNBytes = subjectDN.getBytes(Charset.forName("UTF-8"));
    SystemDerivedKeySpecType spec = config.getSubjectDerivedKeySpec();

    DerivedKey derivedKey = derivedKeyCryptoService.apply(subjectDNBytes, spec.getSalt(), null,
            CryptoProfile.Static.of(spec.getCryptoProfile()));
    byte[] distinguishedNameDigest = derivedKey.getDerivedKey();
    CertificateSubject certificateSubject = certificateSubjectDAO
            .retrieveByDistinguishedNameDigest(distinguishedNameDigest);
    if (certificateSubject == null) {
        // Create it
        certificateSubject = new CertificateSubject();
        certificateSubject.setDistinguishedNameDigest(distinguishedNameDigest);
        certificateSubjectDAO.create(certificateSubject);
    }

    DigitalCertificate digitalCertificate = digitalCertificateDAO
            .retrieveBySubjectAndSignature(certificateSubject, signature);
    if (digitalCertificate == null) {
        digitalCertificate = new DigitalCertificate();
        digitalCertificate.setActive(Boolean.TRUE);
        digitalCertificate.setCertificateSubject(certificateSubject);
        digitalCertificate.setCreated(certificate.getNotBefore());
        digitalCertificate.setExpires(certificate.getNotAfter());
        digitalCertificate.setSignature(signature);
        digitalCertificateDAO.create(digitalCertificate);
    }

    // Perform some checks
    if (BooleanUtils.isNotTrue(digitalCertificate.getActive())) {
        throw new DisabledException(
                String.format("The certficate with id '%s' has been disabled", digitalCertificate.getId()));
    }
    if (digitalCertificate.getExpires().before(new Date())) {
        throw new CredentialsExpiredException(String.format("The certficate with id '%s' expired %tF",
                digitalCertificate.getId(), digitalCertificate.getExpires()));
    }

    // Both of these are transient
    certificateSubject.setCommonName(commonName);
    certificateSubject.setDistinguishedName(subjectDN);
    return digitalCertificate;
}

From source file:net.solarnetwork.node.setup.web.NodeCertificatesController.java

/**
 * View the main certs page./*  w w  w.j a  v  a 2  s.com*/
 * 
 * @param model
 *        the view model
 * @return
 */
@RequestMapping
public String home(Model model) {
    X509Certificate nodeCert = pkiService.getNodeCertificate();
    final Date now = new Date();
    final boolean expired = (nodeCert != null && now.after(nodeCert.getNotAfter()));
    final boolean valid = (nodeCert != null && (!nodeCert.getIssuerDN().equals(nodeCert.getSubjectDN())
            && !now.before(nodeCert.getNotBefore()) && !expired));
    model.addAttribute("nodeCert", nodeCert);
    model.addAttribute("nodeCertExpired", expired);
    model.addAttribute("nodeCertValid", valid);
    return "certs/home";
}

From source file:org.forgerock.openidm.jaspi.modules.IDMUserAuthModule.java

/**
 * Authenticates the request using the client certificate from the request.
 *
 * @param request The ServletRequest./*from w w w .j a  v  a2 s. c  om*/
 * @param authData The AuthData object.
 */
// This is currently Jetty specific
private boolean authenticateUsingClientCert(ServletRequest request, AuthData authData) {

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

    if (certs != null) {
        Principal existingPrincipal = null;
        if (request instanceof HttpServletRequest) {
            ((HttpServletRequest) request).getUserPrincipal();
        }
        logger.debug("Request {} existing Principal {} has {} certificates", request, existingPrincipal,
                certs.length);
        for (X509Certificate cert : certs) {
            logger.debug("Request {} client certificate subject DN: {}", request, cert.getSubjectDN());
        }
    }
    if (certs == null || certs.length == 0 || certs[0] == null) {
        return false;
    }
    authData.setUsername(certs[0].getSubjectDN().getName());
    authData.setUserId(authData.getUsername());
    authData.getRoles().add("openidm-cert");
    logger.debug("Authentication client certificate subject {}", authData.getUsername());
    return true;
}

From source file:org.codice.ddf.security.handler.pki.CrlChecker.java

/**
 * Checks if the provided cert is listed in the CRL.
 *
 * @param certs List of certs to be checked against the CRL
 * @return boolean value Whether or not the client presenting the certs should be let through
 */// w w w .j a va  2s.c  om
private boolean passesCrl(X509Certificate[] certs) {
    if (certs != null) {
        LOGGER.debug("Got {} certificate(s) in the incoming request", certs.length);
        for (X509Certificate curCert : certs) {
            if (crlCache.get() != null && crlCache.get().isRevoked(curCert)) {
                SecurityLogger.audit("Denying access for subject DN: " + curCert.getSubjectDN()
                        + " due to certificate being revoked by CRL.");
                return false;
            }
        }
    } else {
        LOGGER.debug("Allowing message through CRL check. There were no certificates sent by the client.");
        return true;
    }
    return true;
}