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.nifi.toolkit.tls.service.client.TlsCertificateSigningRequestPerformer.java

/**
 * Submits a CSR to the Certificate authority, checks the resulting hmac, and returns the chain if everything succeeds
 *
 * @param keyPair the keypair to generate the csr for
 * @throws IOException if there is a problem during the process
 * @return the resulting certificate chain
 *///w w w  . j a  va 2  s .  c o m
public X509Certificate[] perform(KeyPair keyPair) throws IOException {
    try {
        List<X509Certificate> certificates = new ArrayList<>();

        HttpClientBuilder httpClientBuilder = httpClientBuilderSupplier.get();
        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
        sslContextBuilder.useProtocol("TLSv1.2");

        // We will be validating that we are talking to the correct host once we get the response's hmac of the token and public key of the ca
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        httpClientBuilder.setSSLSocketFactory(new TlsCertificateAuthorityClientSocketFactory(
                sslContextBuilder.build(), caHostname, certificates));

        String jsonResponseString;
        int responseCode;
        try (CloseableHttpClient client = httpClientBuilder.build()) {
            JcaPKCS10CertificationRequest request = TlsHelper.generateCertificationRequest(dn,
                    domainAlternativeNames, keyPair, signingAlgorithm);
            TlsCertificateAuthorityRequest tlsCertificateAuthorityRequest = new TlsCertificateAuthorityRequest(
                    TlsHelper.calculateHMac(token, request.getPublicKey()),
                    TlsHelper.pemEncodeJcaObject(request));

            HttpPost httpPost = new HttpPost();
            httpPost.setEntity(
                    new ByteArrayEntity(objectMapper.writeValueAsBytes(tlsCertificateAuthorityRequest)));

            if (logger.isInfoEnabled()) {
                logger.info("Requesting certificate with dn " + dn + " from " + caHostname + ":" + port);
            }
            try (CloseableHttpResponse response = client.execute(new HttpHost(caHostname, port, "https"),
                    httpPost)) {
                jsonResponseString = IOUtils.toString(
                        new BoundedInputStream(response.getEntity().getContent(), 1024 * 1024),
                        StandardCharsets.UTF_8);
                responseCode = response.getStatusLine().getStatusCode();
            }
        }

        if (responseCode != Response.SC_OK) {
            throw new IOException(
                    RECEIVED_RESPONSE_CODE + responseCode + " with payload " + jsonResponseString);
        }

        if (certificates.size() != 1) {
            throw new IOException(EXPECTED_ONE_CERTIFICATE);
        }

        TlsCertificateAuthorityResponse tlsCertificateAuthorityResponse = objectMapper
                .readValue(jsonResponseString, TlsCertificateAuthorityResponse.class);
        if (!tlsCertificateAuthorityResponse.hasHmac()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_HMAC);
        }

        X509Certificate caCertificate = certificates.get(0);
        byte[] expectedHmac = TlsHelper.calculateHMac(token, caCertificate.getPublicKey());

        if (!MessageDigest.isEqual(expectedHmac, tlsCertificateAuthorityResponse.getHmac())) {
            throw new IOException(UNEXPECTED_HMAC_RECEIVED_POSSIBLE_MAN_IN_THE_MIDDLE);
        }

        if (!tlsCertificateAuthorityResponse.hasCertificate()) {
            throw new IOException(EXPECTED_RESPONSE_TO_CONTAIN_CERTIFICATE);
        }
        X509Certificate x509Certificate = TlsHelper
                .parseCertificate(new StringReader(tlsCertificateAuthorityResponse.getPemEncodedCertificate()));
        x509Certificate.verify(caCertificate.getPublicKey());
        if (logger.isInfoEnabled()) {
            logger.info("Got certificate with dn " + x509Certificate.getSubjectX500Principal());
        }
        return new X509Certificate[] { x509Certificate, caCertificate };
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:org.viafirma.nucleo.X509.X509Handler.java

/**
 * Retorna el certificado emisor del certificado actual
 * /*  w ww  . j  av a2 s.  c  o  m*/
 * @param certificado
 * @param certificadosConfianza
 * @return
 * @throws ExcepcionErrorInterno  No se ha encontrado un certificado asociado vlido.
 */
public X509Certificate getEmisor(X509Certificate certificado, Set<TrustAnchor> certificadosConfianza)
        throws ExcepcionErrorInterno {
    // Si no es un certificado autoemitido
    if (certificado.getIssuerX500Principal().getName()
            .equals(certificado.getSubjectX500Principal().getName())) {
        // El certificado esta autofirmado, no hay emisor.
        return null;
    } else {
        // Busco el emisor indicado.
        for (TrustAnchor trustAnchor : certificadosConfianza) {
            if (trustAnchor.getTrustedCert().getSubjectX500Principal().getName()
                    .equals(certificado.getIssuerX500Principal().getName())) {
                // Encontrado el certificado de confianza.
                return trustAnchor.getTrustedCert();
            }
        }
    }
    log.error("No hay ningun certificado asociado a :" + certificado.getIssuerX500Principal().getName()
            + " es necesaria su instalacin para poder gestionar este tpo de certificados.");
    throw new ExcepcionErrorInterno(CodigoError.ERROR_VALIDACION_AUTORIDAD_NO_RECONOCIDA);
}

From source file:be.fedict.eid.dss.model.bean.AdministratorManagerBean.java

public boolean hasAdminRights(X509Certificate certificate) {
    String id = getId(certificate);
    AdministratorEntity adminEntity = this.entityManager.find(AdministratorEntity.class, id);
    if (null != adminEntity) {
        if (false == adminEntity.isPending()) {
            return true;
        } else {/*  w w  w . j  av  a2 s  .c o m*/
            /*
             * This admin is awaiting approval.
             */
            return false;
        }
    }
    String name = certificate.getSubjectX500Principal().toString();
    if (AdministratorEntity.hasAdmins(this.entityManager)) {
        /*
         * So we register this admin as pending.
         */
        adminEntity = new AdministratorEntity(id, name, true);
        this.entityManager.persist(adminEntity);
        return false;
    }
    /*
     * Else we bootstrap the admin.
     */
    adminEntity = new AdministratorEntity(id, name, false);
    this.entityManager.persist(adminEntity);
    return true;
}

From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest rqst = (HttpServletRequest) request;
    HttpServletResponse rsp = (HttpServletResponse) response;

    if (LOG.isDebugEnabled()) {
        StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/")
                .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort());

        @SuppressWarnings("unchecked")
        Enumeration<String> e = rqst.getAttributeNames();
        for (; e.hasMoreElements();) {
            String attribute = e.nextElement();
            b.append("\n  " + attribute + " => " + rqst.getAttribute(attribute));
        }/*from  w  w w .ja  v  a 2 s  . c  o m*/

        X509Certificate[] userCerts = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");
        if (userCerts != null)
            for (X509Certificate cert : userCerts)
                b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName());

        b.append("\n The Scheme is " + rqst.getScheme());
        b.append("\n The Auth Type is " + rqst.getAuthType());
        b.append("\n The Path Info is " + rqst.getPathInfo());
        b.append("\n The Translated Path Info is " + rqst.getPathTranslated());
        b.append("\n The Context Path is " + rqst.getContextPath());
        b.append("\n The Query String is " + rqst.getQueryString());
        b.append("\n The Remote User is " + rqst.getRemoteUser());
        b.append("\n The User Principal is " + rqst.getUserPrincipal());
        b.append("\n The Request URI is " + rqst.getRequestURI());
        b.append("\n The Request URL is " + rqst.getRequestURL());
        b.append("\n The Servlet Path is " + rqst.getServletPath());

        LOG.debug(b.toString());
    }

    boolean unitTest = false;
    if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null)
        unitTest = true;

    if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) {
        boolean isAuthorized = false;
        X509Certificate[] certs = (X509Certificate[]) rqst
                .getAttribute("javax.servlet.request.X509Certificate");

        if (unitTest) {
            try {
                LOG.debug("==> Entering https unit test");
                String SslPath = rqst.getParameter("SslPath");
                InputStream inStream = new FileInputStream(SslPath);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                inStream.close();
                certs = new X509Certificate[] { cert };
            } catch (Exception e) {
                // do nothing here
            }
        }

        if (certs == null || certs.length == 0) {
            rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received");
            LOG.info("No Client SSL certificate received");
            return;
        }
        for (X509Certificate cert : certs) {
            try {
                cert.checkValidity();
            } catch (CertificateExpiredException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired");
                return;
            } catch (CertificateNotYetValidException e) {
                LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid");
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid");
                return;
            }
        }

        String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*");
        String userID = null;
        for (String s : tokens) {
            if (s.startsWith("CN=")) {
                userID = s;
                break;
            }
        }
        if (userID == null || userID.length() < 4) {
            LOG.info("Can't retrieve user ID from SSL certificate");
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate");
            return;
        }
        userID = userID.substring(3);

        String servletPath = rqst.getServletPath();
        if (unitTest) {
            servletPath = rqst.getParameter("TestSevletPathInfo");
            LOG.info("this is for unit test purpose only");
        }

        if (HFTP_PATTERN.matcher(servletPath).matches()) {
            // request is an HSFTP request
            if (FILEPATH_PATTERN.matcher(servletPath).matches()) {
                // file path as part of the URL
                isAuthorized = checkPath(userID, certs[0],
                        rqst.getPathInfo() != null ? rqst.getPathInfo() : "/");
            } else {
                // file path is stored in "filename" parameter
                isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename"));
            }
        } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) {
            Configuration conf = new Configuration(false);
            conf.addResource("hdfsproxy-default.xml");
            Map<String, Set<Path>> permsMap = getPermMap(conf);
            Map<String, Set<BigInteger>> certsMap = getCertsMap(conf);
            if (permsMap == null || certsMap == null) {
                LOG.warn("Permission files reloading failed");
                rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        "Permission files reloading failed");
                return;
            }
            ProxyFilter.permsMap = permsMap;
            ProxyFilter.certsMap = certsMap;
            LOG.info("User permissions and user certs files reloaded");
            rsp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        if (!isAuthorized) {
            rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access");
            return;
        }

        // request is authorized, set ugi for servlets
        UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID);
        rqst.setAttribute("authorized.ugi", ugi);
        rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID);
    } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes
        String ugi = rqst.getParameter("ugi");
        if (ugi != null) {
            rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi));
            rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]);
        }
    }
    chain.doFilter(request, response);
}

From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java

@Test
public void testIssueCert() throws IOException, CertificateException, NoSuchAlgorithmException,
        OperatorCreationException, NoSuchProviderException, InvalidKeyException, SignatureException {
    X509Certificate issuer = loadCertificate(
            new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.crt")));
    KeyPair issuerKeyPair = loadKeyPair(
            new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.key")));

    String dn = "CN=testIssued, O=testOrg";

    KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize);
    X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn, keyPair.getPublic(),
            issuer, issuerKeyPair, signingAlgorithm, days);
    assertEquals(dn, x509Certificate.getSubjectX500Principal().toString());
    assertEquals(issuer.getSubjectX500Principal().toString(),
            x509Certificate.getIssuerX500Principal().toString());
    assertEquals(keyPair.getPublic(), x509Certificate.getPublicKey());

    Date notAfter = x509Certificate.getNotAfter();
    assertTrue(notAfter.after(inFuture(days - 1)));
    assertTrue(notAfter.before(inFuture(days + 1)));

    Date notBefore = x509Certificate.getNotBefore();
    assertTrue(notBefore.after(inFuture(-1)));
    assertTrue(notBefore.before(inFuture(1)));

    assertEquals(signingAlgorithm, x509Certificate.getSigAlgName());
    assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm());

    x509Certificate.verify(issuerKeyPair.getPublic());
}

From source file:org.wso2.carbon.identity.certificateauthority.crl.CrlFactory.java

/**
 * @param caCert              Certoficate authority's certificate
 * @param caKey               CA private key
 * @param revokedCertificates list of revoked certificates
 * @param crlNumber           unique number of the crl
 * @param baseCrlNumber       base crl number
 * @param isDeltaCrl          whether the crl is a delta crl or a full crl
 * @return returns the X509 Crl/*w ww  .  ja  va 2 s  .  co m*/
 * @throws Exception
 */
private X509CRL createCRL(X509Certificate caCert, PrivateKey caKey, RevokedCertificate[] revokedCertificates,
        int crlNumber, int baseCrlNumber, boolean isDeltaCrl) throws Exception {
    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    Date now = new Date();
    CertificateDAO certificateDAO = new CertificateDAO();
    RevocationDAO revocationDAO = new RevocationDAO();
    crlGen.setIssuerDN(caCert.getSubjectX500Principal());
    crlGen.setThisUpdate(now);
    crlGen.setNextUpdate(new Date(now.getTime() + CRL_UPDATE_TIME));
    crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    for (RevokedCertificate cert : revokedCertificates) {
        BigInteger serialNo = new BigInteger(cert.getSerialNo());
        crlGen.addCRLEntry(serialNo, cert.getRevokedDate(), cert.getReason());
    }
    crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(crlNumber)));
    if (isDeltaCrl) {
        crlGen.addExtension(X509Extensions.DeltaCRLIndicator, true,
                new CRLNumber(BigInteger.valueOf(baseCrlNumber)));
    }
    return crlGen.generateX509CRL(caKey, "BC");
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OPCKeySelector.java

@Override
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method,
        XMLCryptoContext context) throws KeySelectorException {
    try {// w w w.jav  a  2  s .co  m
        return super.select(keyInfo, purpose, method, context);
    } catch (KeySelectorException e) {
        LOG.debug("no key found via ds:KeyInfo key selector");
    }
    LOG.debug("signature resource name: " + this.signatureResourceName);
    String signatureSegment = this.signatureResourceName.substring(0,
            this.signatureResourceName.lastIndexOf("/"));
    LOG.debug("signature segment: " + signatureSegment);
    String signatureBase = this.signatureResourceName
            .substring(this.signatureResourceName.lastIndexOf("/") + 1);
    LOG.debug("signature base: " + signatureBase);
    String signatureRelationshipResourceName = signatureSegment + "/_rels/" + signatureBase + ".rels";
    LOG.debug("signature relationship resource name: " + signatureRelationshipResourceName);

    ZipArchiveInputStream zipInputStream;
    try {
        zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true);
    } catch (IOException e) {
        throw new KeySelectorException(e);
    }
    ZipArchiveEntry zipEntry;
    try {
        while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
            if (signatureRelationshipResourceName.equals(zipEntry.getName())) {
                break;
            }
        }
    } catch (IOException e) {
        throw new KeySelectorException(e);
    }
    if (null == zipEntry) {
        LOG.warn("relationship part not present: " + signatureRelationshipResourceName);
        throw new KeySelectorException("no key found");
    }
    LOG.debug("signature relationship part found");

    JAXBElement<CTRelationships> signatureRelationshipsElement;
    try {
        signatureRelationshipsElement = (JAXBElement<CTRelationships>) this.relationshipsUnmarshaller
                .unmarshal(zipInputStream);
    } catch (JAXBException e) {
        throw new KeySelectorException(e);
    }
    CTRelationships signatureRelationships = signatureRelationshipsElement.getValue();
    List<CTRelationship> signatureRelationshipList = signatureRelationships.getRelationship();
    List<String> certificateResourceNames = new LinkedList<String>();
    for (CTRelationship signatureRelationship : signatureRelationshipList) {
        if (DIGITAL_SIGNATURE_CERTIFICATE_REL_TYPE.equals(signatureRelationship.getType())) {
            String certificateResourceName = signatureRelationship.getTarget().substring(1);
            certificateResourceNames.add(certificateResourceName);
        }
    }

    X509Certificate endEntityCertificate = null;

    for (String certificateResourceName : certificateResourceNames) {
        try {
            zipInputStream = new ZipArchiveInputStream(this.opcUrl.openStream(), "UTF8", true, true);
        } catch (IOException e) {
            throw new KeySelectorException(e);
        }
        try {
            while (null != (zipEntry = zipInputStream.getNextZipEntry())) {
                if (certificateResourceName.equals(zipEntry.getName())) {
                    break;
                }
            }
        } catch (IOException e) {
            throw new KeySelectorException(e);
        }
        if (null == zipEntry) {
            LOG.warn("certificate part not present: " + certificateResourceName);
            continue;
        }
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) this.certificateFactory.generateCertificate(zipInputStream);
        } catch (CertificateException e) {
            throw new KeySelectorException(e);
        }
        LOG.debug("certificate subject: " + certificate.getSubjectX500Principal());
        if (-1 != certificate.getBasicConstraints()) {
            LOG.debug("skipping CA certificate");
            continue;
        }
        if (null != endEntityCertificate) {
            throw new KeySelectorException("two possible end entity certificates");
        }
        endEntityCertificate = certificate;
    }
    if (null == endEntityCertificate) {
        throw new KeySelectorException("no key found");
    }
    this.certificate = endEntityCertificate;
    return this;
}

From source file:edu.vt.middleware.ldap.ssl.DefaultHostnameVerifier.java

/**
 * Verify if the hostname is an IP address using
 * {@link LdapUtil#isIPAddress(String)}. Delegates to
 * {@link #verifyIP(String, X509Certificate)} and
 * {@link #verifyDNS(String, X509Certificate)} accordingly.
 *
 * @param  hostname  to verify//from w w w. ja v a2s. c o  m
 * @param  cert  to verify hostname against
 *
 * @return  whether hostname is valid for the supplied certificate
 */
public boolean verify(final String hostname, final X509Certificate cert) {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Verify with the following parameters:");
        this.logger.debug("  hostname = " + hostname);
        this.logger.debug("  cert = " + cert.getSubjectX500Principal().toString());
    }
    boolean b = false;
    if (LdapUtil.isIPAddress(hostname)) {
        b = verifyIP(hostname, cert);
    } else {
        b = verifyDNS(hostname, cert);
    }
    return b;
}

From source file:ddf.security.sts.SubjectDNConstraintsInterceptor.java

/**
 * Checks the certificate against the list of regular expressions given. Only matching one of the
 * regular expressions is necessary.//from w w  w  . jav a  2s . c o  m
 *
 * @param cert
 * @param subjectDNPatterns
 * @return true if the certificate matches the constraints
 */
protected boolean matches(final X509Certificate cert, final Collection<Pattern> subjectDNPatterns) {
    if (subjectDNPatterns == null || subjectDNPatterns.isEmpty()) {
        LOGGER.warn("No Subject DN Certificate Constraints were defined. This could be a security issue");
    } else {
        if (cert == null) {
            LOGGER.debug("The certificate is null so no constraints matching was possible");
            return false;
        }
        String subjectName = cert.getSubjectX500Principal().getName();

        for (Pattern subjectDNPattern : subjectDNPatterns) {
            final Matcher matcher = subjectDNPattern.matcher(subjectName);
            if (matcher.matches()) {
                LOGGER.debug("Subject DN {} matches with pattern {}", subjectName, subjectDNPattern);
                return true;
            }
        }
        return false;
    }

    return true;
}

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

private String getUserIdentifier(X509Certificate certificate) {
    X500Principal userPrincipal = certificate.getSubjectX500Principal();
    String name = userPrincipal.toString();
    int serialNumberBeginIdx = name.indexOf("SERIALNUMBER=");
    if (-1 == serialNumberBeginIdx) {
        throw new SecurityException("SERIALNUMBER not found in X509 CN");
    }//  w w w  . j a v a 2s .  co  m
    int serialNumberValueBeginIdx = serialNumberBeginIdx + "SERIALNUMBER=".length();
    int serialNumberValueEndIdx = name.indexOf(",", serialNumberValueBeginIdx);
    if (-1 == serialNumberValueEndIdx) {
        serialNumberValueEndIdx = name.length();
    }
    String userId = name.substring(serialNumberValueBeginIdx, serialNumberValueEndIdx);
    return userId;
}