Example usage for java.security.cert X509Certificate getSubjectX500Principal

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

Introduction

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

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java

private KeyInfo getKeyInfo(XMLSignatureFactory signFactory, PrivateKeyEntry keyEntry) {

    X509Certificate cert = (X509Certificate) keyEntry.getCertificate();

    KeyInfoFactory kif = signFactory.getKeyInfoFactory();
    List<Object> x509Content = new ArrayList<Object>();
    x509Content.add(cert.getSubjectX500Principal().getName());
    x509Content.add(cert);//from w  w w  . java2 s .  co m
    X509Data xd = kif.newX509Data(x509Content);
    return kif.newKeyInfo(Collections.singletonList(xd));
}

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

/**
 * Loads the trusted certificate authorities according to the specified properties.
 *
 * @param properties properties/*from  ww  w.j a v  a 2 s. c  o m*/
 * @return map of certificate authorities
 */
private Map<String, X509Certificate> getTrustedCAs(final NiFiProperties properties) {
    final Map<String, X509Certificate> certificateAuthorities = new HashMap<>();

    // get the path to the truststore
    final String truststorePath = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE);
    if (truststorePath == null) {
        throw new IllegalArgumentException("The truststore path is required.");
    }

    // get the truststore password
    final char[] truststorePassword;
    final String rawTruststorePassword = properties.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD);
    if (rawTruststorePassword == null) {
        truststorePassword = new char[0];
    } else {
        truststorePassword = rawTruststorePassword.toCharArray();
    }

    // load the configured truststore
    try (final FileInputStream fis = new FileInputStream(truststorePath)) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(KeyStore.getDefaultType());
        truststore.load(fis, truststorePassword);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        // consider any certificates in the truststore as a trusted ca
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                for (X509Certificate ca : ((X509TrustManager) trustManager).getAcceptedIssuers()) {
                    certificateAuthorities.put(ca.getSubjectX500Principal().getName(), ca);
                }
            }
        }
    } catch (final Exception e) {
        throw new IllegalStateException("Unable to load the configured truststore: " + e);
    }

    return certificateAuthorities;
}

From source file:org.sinekartads.smartcard.SmartCardAccess.java

public String[] certificateList() throws SmartCardAccessException {
    // Parse the certificate aliases
    String alias;/*from w  w  w  .  j  a  v a 2  s  . c o  m*/
    List<String> aliases = new ArrayList<String>();
    X509Certificate cert;
    for (X509PublicKeyCertificate iaikCert : iaikCertificateList()) {
        cert = toX509Certificate(iaikCert);
        if (cert.getKeyUsage()[1]) {
            alias = DNParser.parse(cert.getSubjectX500Principal().getName(), "CN");
            aliases.add(alias);
        }
    }

    // return the aliases as an array
    return aliases.toArray(new String[aliases.size()]);
}

From source file:org.wso2.carbon.identity.authenticator.x509Certificate.X509CertificateAuthenticator.java

/**
 * Validate the certificate./*www . j  a v a 2s  .  c om*/
 *
 * @param httpServletRequest    http request
 * @param httpServletResponse   http response
 * @param authenticationContext authentication context
 * @throws AuthenticationFailedException
 */
@Override
protected void processAuthenticationResponse(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, AuthenticationContext authenticationContext)
        throws AuthenticationFailedException {
    Object object = httpServletRequest.getAttribute(X509CertificateConstants.X_509_CERTIFICATE);
    if (object != null) {
        X509Certificate[] certificates;
        if (object instanceof X509Certificate[]) {
            certificates = (X509Certificate[]) object;
        } else {
            throw new AuthenticationFailedException("Exception while casting the X509Certificate");
        }
        if (certificates.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("X509 Certificate Checking in servlet is done! ");
            }
            X509Certificate cert = certificates[0];
            String certAttributes = String.valueOf(cert.getSubjectX500Principal());
            Map<ClaimMapping, String> claims;
            claims = getSubjectAttributes(authenticationContext, certAttributes);
            String alternativeName;
            String subjectAttribute;
            if (alternativeNamePattern != null) {
                alternativeName = getMatchedAlternativeName(cert, authenticationContext);
                validateUsingSubject(alternativeName, authenticationContext, cert, claims);
                if (log.isDebugEnabled()) {
                    log.debug("Certificate validated using the alternative name: " + alternativeName);
                }
                authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_USERNAME,
                        alternativeName);
            } else if (subjectAttributePattern != null) {
                subjectAttribute = getMatchedSubjectAttribute(certAttributes, authenticationContext);
                validateUsingSubject(subjectAttribute, authenticationContext, cert, claims);
                if (log.isDebugEnabled()) {
                    log.debug("Certificate validated using the certificate subject attribute: "
                            + subjectAttribute);
                }
                authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_USERNAME,
                        subjectAttribute);
            } else {
                String userName = (String) authenticationContext
                        .getProperty(X509CertificateConstants.X509_CERTIFICATE_USERNAME);
                if (StringUtils.isEmpty(userName)) {
                    authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_ERROR_CODE,
                            X509CertificateConstants.USERNAME_NOT_FOUND_FOR_X509_CERTIFICATE_ATTRIBUTE);
                    throw new AuthenticationFailedException(
                            "Couldn't find the username for X509Certificate's attribute");
                } else {
                    validateUsingSubject(userName, authenticationContext, cert, claims);
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "Certificate validated using the certificate username attribute: " + userName);
                    }
                }
            }
        } else {
            throw new AuthenticationFailedException("X509Certificate object is null");
        }
    } else {
        authenticationContext.setProperty(X509CertificateConstants.X509_CERTIFICATE_ERROR_CODE,
                X509CertificateConstants.X509_CERTIFICATE_NOT_FOUND_ERROR_CODE);
        throw new AuthenticationFailedException("Unable to find X509 Certificate in browser");
    }
}

From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from  w w w .ja  va 2  s . c  o  m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        /*
              if (this.log.isDebugEnabled()) {
                this.log.debug("Secure session established");
                this.log.debug(" negotiated protocol: " + session.getProtocol());
                this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());
                
                try {
                
                  final Certificate[] certs = session.getPeerCertificates();
                  final X509Certificate x509 = (X509Certificate) certs[0];
                  final X500Principal peer = x509.getSubjectX500Principal();
                
                  this.log.debug(" peer principal: " + peer.toString());
                  final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                  if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                      if (!aC.isEmpty()) {
        altNames.add((String) aC.get(1));
                      }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                  }
                
                  final X500Principal issuer = x509.getIssuerX500Principal();
                  this.log.debug(" issuer principal: " + issuer.toString());
                  final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                  if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                      if (!aC.isEmpty()) {
        altNames.add((String) aC.get(1));
                      }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                  }
                } catch (Exception ignore) {
                }
              }
        */

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:test.unit.be.fedict.eid.applet.service.signer.OOXMLSignatureVerifierTest.java

@Test
public void testGetSigners() throws Exception {
    // setup//ww w  . ja v  a 2 s .  c o  m
    URL url = OOXMLSignatureVerifierTest.class.getResource("/hello-world-signed-twice.docx");

    // operate
    OOXMLSignatureVerifier verifier = new OOXMLSignatureVerifier();
    List<X509Certificate> result = verifier.getSigners(url);

    // verify
    assertNotNull(result);
    assertEquals(2, result.size());
    X509Certificate signer1 = result.get(0);
    X509Certificate signer2 = result.get(1);
    LOG.debug("signer 1: " + signer1.getSubjectX500Principal());
    LOG.debug("signer 2: " + signer2.getSubjectX500Principal());
}

From source file:org.xdi.oxauth.cert.validation.OCSPCertificateVerifier.java

@Override
public ValidationStatus validate(X509Certificate certificate, List<X509Certificate> issuers,
        Date validationDate) {/*from  w  ww .j  a  v a  2 s.c o  m*/
    X509Certificate issuer = issuers.get(0);
    ValidationStatus status = new ValidationStatus(certificate, issuer, validationDate,
            ValidatorSourceType.OCSP, CertificateValidity.UNKNOWN);

    try {
        Principal subjectX500Principal = certificate.getSubjectX500Principal();

        String ocspUrl = getOCSPUrl(certificate);
        if (ocspUrl == null) {
            log.error("OCSP URL for '" + subjectX500Principal + "' is empty");
            return status;
        }

        log.debug("OCSP URL for '" + subjectX500Principal + "' is '" + ocspUrl + "'");

        DigestCalculator digestCalculator = new JcaDigestCalculatorProviderBuilder().build()
                .get(CertificateID.HASH_SHA1);
        CertificateID certificateId = new CertificateID(digestCalculator,
                new JcaX509CertificateHolder(certificate), certificate.getSerialNumber());

        // Generate OCSP request
        OCSPReq ocspReq = generateOCSPRequest(certificateId);

        // Get OCSP response from server
        OCSPResp ocspResp = requestOCSPResponse(ocspUrl, ocspReq);
        if (ocspResp.getStatus() != OCSPRespBuilder.SUCCESSFUL) {
            log.error("OCSP response is invalid!");
            status.setValidity(CertificateValidity.INVALID);
            return status;
        }

        boolean foundResponse = false;
        BasicOCSPResp basicOCSPResp = (BasicOCSPResp) ocspResp.getResponseObject();
        SingleResp[] singleResps = basicOCSPResp.getResponses();
        for (SingleResp singleResp : singleResps) {
            CertificateID responseCertificateId = singleResp.getCertID();
            if (!certificateId.equals(responseCertificateId)) {
                continue;
            }

            foundResponse = true;

            log.debug("OCSP validationDate: " + validationDate);
            log.debug("OCSP thisUpdate: " + singleResp.getThisUpdate());
            log.debug("OCSP nextUpdate: " + singleResp.getNextUpdate());

            status.setRevocationObjectIssuingTime(basicOCSPResp.getProducedAt());

            Object certStatus = singleResp.getCertStatus();
            if (certStatus == CertificateStatus.GOOD) {
                log.debug("OCSP status is valid for '" + certificate.getSubjectX500Principal() + "'");
                status.setValidity(CertificateValidity.VALID);
            } else {
                if (singleResp.getCertStatus() instanceof RevokedStatus) {
                    log.warn("OCSP status is revoked for: " + subjectX500Principal);
                    if (validationDate
                            .before(((RevokedStatus) singleResp.getCertStatus()).getRevocationTime())) {
                        log.warn("OCSP revocation time after the validation date, the certificate '"
                                + subjectX500Principal + "' was valid at " + validationDate);
                        status.setValidity(CertificateValidity.VALID);
                    } else {
                        Date revocationDate = ((RevokedStatus) singleResp.getCertStatus()).getRevocationTime();
                        log.info("OCSP for certificate '" + subjectX500Principal + "' is revoked since "
                                + revocationDate);
                        status.setRevocationDate(revocationDate);
                        status.setRevocationObjectIssuingTime(singleResp.getThisUpdate());
                        status.setValidity(CertificateValidity.REVOKED);
                    }
                }
            }
        }

        if (!foundResponse) {
            log.error("There is no matching OCSP response entries");
        }
    } catch (Exception ex) {
        log.error("OCSP exception: ", ex);
    }

    return status;
}

From source file:org.alfresco.web.scripts.servlet.X509ServletFilterBase.java

private boolean validCert(X509Certificate[] certs) {
    /*/*from  w  w  w . j a va2s . c  om*/
    * If the cert is null then the it's not valid.
    */

    if (certs == null) {
        return false;
    }

    /*
    * Get the first certificate in the chain. The first certificate is the client certificate.
    */

    X509Certificate cert = certs[0];
    try {
        /*
        * check the certificate has not expired.
        */
        if (logger.isDebugEnabled()) {
            logger.debug("Checking cert is valid");
        }
        cert.checkValidity();
    } catch (Exception e) {
        logger.error("Cert is invalid", e);
        return false;
    }

    X500Principal x500Principal = cert.getSubjectX500Principal();
    String name = x500Principal.getName();

    /*
    * Cert contains is an optional check
    */

    if (this.certContains == null) {
        return true;
    }

    /*
    * Check that the cert contains the specified value.
    */

    if (name.contains(this.certContains)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Cert: " + name + "  contains:  " + this.certContains);
        }

        return true;
    } else {
        logger.error("Cert: " + name + "  does not contain:  " + this.certContains);
        return false;
    }
}

From source file:be.fedict.eid.idp.model.admin.AdminManagerBean.java

public boolean isAdmin(X509Certificate certificate) {

    String id = getId(certificate);
    AdministratorEntity adminEntity = this.entityManager.find(AdministratorEntity.class, id);
    if (null != adminEntity && !adminEntity.isPending()) {
        return true;
    } else if (null != adminEntity) {
        // admin exist but is not yet approvied
        return false;
    }//from w w  w  .j  ava  2 s .  co  m
    if (AdministratorEntity.hasAdmins(this.entityManager)) {
        /*
         * We register a 'pending' admin.
         */
        String name = certificate.getSubjectX500Principal().toString();
        adminEntity = new AdministratorEntity(id, name, true);
        this.entityManager.persist(adminEntity);
        return false;
    }
    /*
     * Else we bootstrap the admin.
     */
    String name = certificate.getSubjectX500Principal().toString();
    adminEntity = new AdministratorEntity(id, name);
    this.entityManager.persist(adminEntity);
    return true;
}

From source file:org.apache.nifi.web.security.x509.ocsp.OcspCertificateValidator.java

public OcspCertificateValidator(final NiFiProperties properties) {
    // get the responder url
    final String rawValidationAuthorityUrl = properties.getProperty(NiFiProperties.SECURITY_OCSP_RESPONDER_URL);

    // set properties when appropriate
    if (StringUtils.isNotBlank(rawValidationAuthorityUrl)) {
        try {/*from   www  .  ja  va 2 s. c  om*/
            // attempt to parse the specified va url
            validationAuthorityURI = URI.create(rawValidationAuthorityUrl);

            // connection details
            final ClientConfig config = new DefaultClientConfig();
            config.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, READ_TIMEOUT);
            config.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, CONNECT_TIMEOUT);

            // initialize the client
            if (HTTPS.equalsIgnoreCase(validationAuthorityURI.getScheme())) {
                client = WebUtils.createClient(config, SslContextFactory.createSslContext(properties));
            } else {
                client = WebUtils.createClient(config);
            }

            // get the trusted CAs
            trustedCAs = getTrustedCAs(properties);

            // consider the ocsp certificate is specified
            final X509Certificate ocspCertificate = getOcspCertificate(properties);
            if (ocspCertificate != null) {
                trustedCAs.put(ocspCertificate.getSubjectX500Principal().getName(), ocspCertificate);
            }

            // TODO - determine how long to cache the ocsp responses for
            final long cacheDurationMillis = FormatUtils.getTimeDuration("12 hours", TimeUnit.MILLISECONDS);

            // build the ocsp cache
            ocspCache = CacheBuilder.newBuilder().expireAfterWrite(cacheDurationMillis, TimeUnit.MILLISECONDS)
                    .build(new CacheLoader<OcspRequest, OcspStatus>() {
                        @Override
                        public OcspStatus load(OcspRequest ocspRequest) throws Exception {
                            final String subjectDn = ocspRequest.getSubjectCertificate()
                                    .getSubjectX500Principal().getName();

                            logger.info(
                                    String.format("Validating client certificate via OCSP: <%s>", subjectDn));
                            final OcspStatus ocspStatus = getOcspStatus(ocspRequest);
                            logger.info(String.format("Client certificate status for <%s>: %s", subjectDn,
                                    ocspStatus.toString()));

                            return ocspStatus;
                        }
                    });
        } catch (final Exception e) {
            logger.error("Disabling OCSP certificate validation. Unable to load OCSP configuration: " + e, e);
            client = null;
        }
    }
}