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:org.viafirma.nucleo.validacion.OcspValidatorHandler.java

/**
 * Retorna el CN de un certificado./* ww  w . ja va  2 s .co m*/
 * 
 * @param certificadoResponseOCSP
 * @return
 */
private String getCN(X509Certificate certificadoResponseOCSP) {
    // ej: C=ES,O=DIRECCION GENERAL DE LA POLICIA,OU=DNIE,OU=FNMT,CN=AV DNIE
    // FNMT
    // cn:AV DNIE FNMT
    String cn = StringUtils.substringBetween(certificadoResponseOCSP.getSubjectDN().getName(), "CN=", ",");
    if (cn == null) {
        // Puede que este al final de Subcjet
        cn = StringUtils.substringAfterLast(certificadoResponseOCSP.getSubjectDN().getName(), "CN=");
    }
    return cn;
}

From source file:org.ovirt.engine.core.utils.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//from   w  w w  .j  a v  a2s  .  c om
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = 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<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = 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("SSLv3");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new AuthSSLInitializationException(
                "I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

private void logCertificateContents(Certificate cert) {
    if (cert instanceof X509Certificate) {
        X509Certificate x509Cert = (X509Certificate) cert;
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug(" X509 Certificate :");
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Subject DN: " + x509Cert.getSubjectDN());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class)
                .debug("  Signature Algorithm: " + x509Cert.getSigAlgName());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class)
                .debug("  Signature: " + x509Cert.getPublicKey().toString());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Valid from: " + x509Cert.getNotBefore());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Valid until: " + x509Cert.getNotAfter());
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("  Issuer: " + x509Cert.getIssuerDN());
    } else/* ww  w. j a  v  a2s  .  co  m*/
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug(" Certificate :" + cert.getType());
}

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

/**
 * Retorna un certificado generico parseando los datos de un certificado X509
 * @param certificadoX509 /*from  w  ww.j av  a  2 s  .c  o  m*/
 * @return
 */
public CertificadoGenerico generar(X509Certificate certificadoX509) {
    CertificadoGenerico certificado = new CertificadoGenerico();

    // recuperamos el conjunto de oids
    Map<String, String> propiedadesOid = X509Handler.getCurrentInstance().readPropertiesOid(certificadoX509);

    String subject = certificadoX509.getSubjectDN().toString();

    // parseo el subject
    //StringTokenizer tokenizer=new StringTokenizer(subject,",\"");
    //String [] tokens=subject.split(",");
    //for (int i = 0; i < tokens.length; i++) {
    //   String parIdValor = tokens[i].trim();
    //   String id= parIdValor.split("=")[0];
    //   String valor= parIdValor.split("=")[1];
    //   propiedadesOid.put(id,valor);
    //}
    loadPropiedadesOid(subject, propiedadesOid);

    // guardo todas las propiedades(pintables)
    Set<String> keys = propiedadesOid.keySet();
    for (Iterator<String> iter = keys.iterator(); iter.hasNext();) {
        String key = iter.next();
        String valor = propiedadesOid.get(key);
        // FIX: Problema con el encondig utf-8 en openid.
        String newValue = StringUtils.replaceChars(valor, "??", "aeiounuAEIOU");
        if (!StringUtils.isAsciiPrintable(newValue)) {
            // omitimos el campo 
            iter.remove();
        } else {
            // remplazamos el valor
            propiedadesOid.put(key, newValue);
        }
    }
    certificado.setPropiedades(propiedadesOid);

    // identifico el nombre de la CA propietaria del certificado
    certificado.setCa(certificadoX509.getIssuerDN().getName());

    certificado.setNombre(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.1"));
    certificado.setApellido1(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.2"));
    certificado.setApellido2(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.3"));
    certificado.setNumberUserId(certificado.getPropiedades().get("1.3.6.1.4.1.5734.1.4"));
    certificado.setCn(propiedadesOid.get("CN"));

    // si no hemos recuperado el nombre en la extensin lo intento recuperar del GIVENNAME.
    if (StringUtils.isEmpty(certificado.getNombre())) {
        certificado.setNombre(propiedadesOid.get("GIVENNAME"));
    }

    // si no hemos recuperado el nombre APELLIDO.
    if (StringUtils.isEmpty(certificado.getApellido1())) {
        certificado.setApellido1(propiedadesOid.get("SURNAME"));
    }

    // si no tenemos apelligos, los intentamos recuperar del CN ( cado del edni)
    // CN="Apelido1 apellido2, nombre (AUTENTICACIN)",
    if (StringUtils.isEmpty(certificado.getApellido1())) {
        // TODO, no se recupera correctamente el CN, pero el resultado es el correcto.
        // Debera de ser StringUtils.substringAfterLast(propiedadesOid.get("CN").replaceAll("\"", ""),",")
        // pero nos vale con propiedadesOid.get("CN")
        certificado.setApellido1(propiedadesOid.get("CN"));
    }

    // si no hemos recuperado el nombre NIF.
    if (StringUtils.isEmpty(certificado.getNumberUserId())) {
        certificado.setNumberUserId(propiedadesOid.get("SERIALNUMBER"));
    }

    // si no hemos recuperado el nombre email.
    if (StringUtils.isEmpty(certificado.getEmail())) {
        certificado.setEmail(certificado.getPropiedades().get(OID_EMAIL));
    }

    // si sige siendo null lo recupero del oid
    if (StringUtils.isEmpty(certificado.getEmail())) {
        certificado.setEmail(propiedadesOid.get("EMAILADDRESS"));
    }

    // si no hemos recuperado el pais
    if (StringUtils.isEmpty(certificado.getPais())) {
        certificado.setPais(certificado.getPropiedades().get("C"));
    }

    // filtrado para que ningun campo sea null
    if (certificado.getApellido1() == null) {
        certificado.setApellido1("");
    }

    if (certificado.getApellido2() == null) {
        certificado.setApellido2("");
    }

    if (certificado.getCa() == null) {
        certificado.setCa("");
    }
    if (certificado.getEmail() == null) {
        certificado.setEmail("");
    }
    if (certificado.getNombre() == null) {
        certificado.setNombre("");
    }
    if (certificado.getPais() == null) {
        certificado.setPais("");
    }

    if (certificado.getNumberUserId() == null) {
        certificado.setNumberUserId("");
    }

    // recupero el cargo. 
    String cargo = propiedadesOid.get("T");
    if (cargo != null) {
        certificado.setCargo(cargo);
    }
    // recupero el nombre de la organizacin.
    String organizacion = propiedadesOid.get("O");
    if (organizacion != null) {
        certificado.setOrganizacion(organizacion);
    }

    // Detectamos si el certificado est caducado
    Date hoy = new Date();
    if (certificadoX509.getNotAfter().before(hoy)) {
        // el certificado est caducado.
        certificado.setCaducado(true);
    }

    // recuperar el tpo de certificado
    loadTipoCertificado(certificado, propiedadesOid, certificado.getCa());

    return certificado;
}

From source file:org.ejbca.extra.ra.ScepRAServlet.java

private void getCACertChain(String message, String remoteAddr, HttpServletResponse response, String alias,
        KeyStore raks, boolean getcaracertchain)
        throws KeyStoreException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertStoreException, CMSException, IOException, Exception {
    Certificate[] chain = raks.getCertificateChain(alias);
    log.debug("CACertChain is of length: " + chain.length);
    if (chain != null) {
        X509Certificate cert = (X509Certificate) raks.getCertificateChain(alias)[0];
        log.debug("Found cert with DN '" + cert.getSubjectDN().toString() + "'");
        //            X509Certificate racert = (X509Certificate) raks.getCertificate(alias);
        //            PrivateKey rapriv = (PrivateKey) raks.getKey(alias, keystorepwd.toCharArray());
        byte[] pkcs7response = createPKCS7(chain, null, null);
        String ctype = "application/x-x509-ca-ra-cert";
        if (getcaracertchain) {
            ctype = "application/x-x509-ca-ra-cert-chain";
        }/*from ww  w .  j  av a2s . c  o m*/
        log.debug("Sent certificate(s) for CA/RA '" + message + "' to SCEP client with ip " + remoteAddr
                + ". Using content-type: " + ctype);
        sendBinaryBytes(pkcs7response, response, ctype, null);
    } else {
        log.error("No CA certificates found");
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found.");
    }
}

From source file:hk.hku.cecid.ebms.admin.listener.PartnershipPageletAdaptor.java

private void getCertificateForPartnership(byte[] cert, PropertyTree dom, String prefix) {
    if (cert != null) {
        try {//from   w  w  w . j av  a 2  s  . co m
            ByteArrayInputStream bais = new ByteArrayInputStream(cert);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509Certificate verifyCert = (X509Certificate) cf.generateCertificate(bais);
            bais.close();
            dom.setProperty(prefix + "issuer", verifyCert.getIssuerDN().getName());
            dom.setProperty(prefix + "subject", verifyCert.getSubjectDN().getName());
            dom.setProperty(prefix + "thumbprint", getCertFingerPrint(verifyCert));
            dom.setProperty(prefix + "valid-from", StringUtilities.toGMTString(verifyCert.getNotBefore()));
            dom.setProperty(prefix + "valid-to", StringUtilities.toGMTString(verifyCert.getNotAfter()));
        } catch (Exception e) {
            dom.setProperty(prefix + "Error", e.toString());
        }
    } else {
        dom.setProperty(prefix, "");
    }
}

From source file:io.kodokojo.config.module.SecurityModule.java

@Provides
@Singleton// w  w w.  j  a va  2 s.  c  om
SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) {
    if (securityConfig == null) {
        throw new IllegalArgumentException("securityConfig must be defined.");
    }
    if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) {

        File pemFile = new File(securityConfig.wildcardPemPath());
        try {
            String content = IOUtils.toString(new FileReader(pemFile));
            String contentPrivate = RSAUtils.extractPrivateKey(content);
            String contentPublic = RSAUtils.extractPublic(content);

            RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate));
            X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic));
            RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();

            X509Certificate[] certificates = new X509Certificate[1];
            certificates[0] = certificate;
            LOGGER.info(
                    "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ",
                    certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath());
            return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e);
        }
    } else {
        try {
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")),
                    System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray());

            RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(),
                    securityConfig.sslRootCaKsPassword().toCharArray());
            if (key == null) {
                return null;
            }

            RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias());
            List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream()
                    .map(c -> (X509Certificate) c).collect(Collectors.toList());
            LOGGER.info(
                    "Using a CA SSL certificat {} from keystore  to provide Certificat to all instances of Kodo Kojo. ",
                    securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore"));
            return new SSLKeyPair(key, publicKey,
                    x509Certificates.toArray(new X509Certificate[x509Certificates.size()]));
        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
                | InvalidKeySpecException | CertificateException | IOException e) {

            throw new RuntimeException("Unable to open default Keystore", e);
        }
    }
}

From source file:org.dataone.proto.trove.mn.http.client.DataHttpClientHandler.java

/**
 * Show details of an X509 certificate, printing the information to STDOUT.
 *
 * @param cert the certificate to be displayed
 *//*from  ww w  . j  a va  2s  . c o  m*/
public void displayCertificate(X509Certificate cert) {
    if (cert == null) {
        return;
    }
    logger.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    Principal issuerDN = cert.getIssuerDN();
    logger.debug(" Issuer: " + issuerDN.toString());
    Date notBefore = cert.getNotBefore();
    DateFormat fmt = SimpleDateFormat.getDateTimeInstance();
    logger.debug("   From: " + fmt.format(notBefore));
    Date notAfter = cert.getNotAfter();
    logger.debug("     To: " + fmt.format(notAfter));
    Principal subjectDN = cert.getSubjectDN();
    logger.debug("Subject: " + subjectDN.toString());
    logger.debug("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}

From source file:org.votingsystem.util.HttpHelper.java

private HttpHelper() {
    try {/*  w  ww .  ja  v a2 s .  c  o  m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLContext sslcontext = null;
        SSLConnectionSocketFactory sslsf = null;
        if (ContextVS.getInstance().getVotingSystemSSLCerts() != null) {
            log.info("loading SSLContext with app certificates");
            X509Certificate sslServerCert = ContextVS.getInstance().getVotingSystemSSLCerts().iterator().next();
            trustStore.setCertificateEntry(sslServerCert.getSubjectDN().toString(), sslServerCert);
            sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
            X509HostnameVerifier hostnameVerifier = (X509HostnameVerifier) new AllowAllHostnameVerifier();
            sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                    hostnameVerifier);
        } else {
            sslcontext = SSLContexts.createSystemDefault();
            sslsf = new SSLConnectionSocketFactory(sslcontext);
            log.info("loading default SSLContext");
        }
        // Create a registry of custom connection socket factories for supported protocol schemes.
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", sslsf).build();
        //Create socket configuration
        //SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
        //Configure the connection manager to use socket configuration either by default or for a specific host.
        //connManager.setDefaultSocketConfig(socketConfig);
        connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry, connFactory, dnsResolver);
        connManager.setMaxTotal(200);
        connManager.setDefaultMaxPerRoute(100);
        connEvictor = new IdleConnectionEvictor(connManager);
        connEvictor.start();
        HttpRoute httpRouteVS = new HttpRoute(new HttpHost("www.sistemavotacion.org", 80));
        connManager.setMaxPerRoute(httpRouteVS, 200);
        /* timeouts with large simulations ->
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(REQUEST_TIME_OUT)
            .setConnectionRequestTimeout(REQUEST_TIME_OUT).setSocketTimeout(REQUEST_TIME_OUT).build();
        httpClient = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(
            requestConfig).build();*/
        httpClient = HttpClients.custom().setConnectionManager(connManager).build();
    } catch (Exception ex) {
        log.log(Level.SEVERE, ex.getMessage(), ex);
    }
}

From source file:org.nuxeo.ecm.platform.signature.core.sign.SignatureServiceImpl.java

@Override
public Blob signPDF(Blob pdfBlob, DocumentModel user, String keyPassword, String reason)
        throws ClientException {
    CertService certService = Framework.getLocalService(CertService.class);
    CUserService cUserService = Framework.getLocalService(CUserService.class);
    try {//from w w  w  .j  ava 2 s .c om
        File outputFile = File.createTempFile("signed-", ".pdf");
        Blob blob = Blobs.createBlob(outputFile, MIME_TYPE_PDF);
        Framework.trackFile(outputFile, blob);

        PdfReader pdfReader = new PdfReader(pdfBlob.getStream());
        List<X509Certificate> pdfCertificates = getCertificates(pdfReader);

        // allows for multiple signatures
        PdfStamper pdfStamper = PdfStamper.createSignature(pdfReader, new FileOutputStream(outputFile), '\0',
                null, true);

        PdfSignatureAppearance pdfSignatureAppearance = pdfStamper.getSignatureAppearance();
        String userID = (String) user.getPropertyValue("user:username");
        AliasWrapper alias = new AliasWrapper(userID);
        KeyStore keystore = cUserService.getUserKeystore(userID, keyPassword);
        Certificate certificate = certService.getCertificate(keystore, alias.getId(AliasType.CERT));
        KeyPair keyPair = certService.getKeyPair(keystore, alias.getId(AliasType.KEY),
                alias.getId(AliasType.CERT), keyPassword);

        if (certificatePresentInPDF(certificate, pdfCertificates)) {
            X509Certificate userX509Certificate = (X509Certificate) certificate;
            String message = ALREADY_SIGNED_BY + userX509Certificate.getSubjectDN();
            log.debug(message);
            throw new AlreadySignedException(message);
        }

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

        Certificate[] certChain = certificates.toArray(new Certificate[0]);
        pdfSignatureAppearance.setCrypto(keyPair.getPrivate(), certChain, null,
                PdfSignatureAppearance.SELF_SIGNED);
        if (StringUtils.isBlank(reason)) {
            reason = getSigningReason();
        }
        pdfSignatureAppearance.setReason(reason);
        pdfSignatureAppearance.setAcro6Layers(true);
        Font layer2Font = FontFactory.getFont(FontFactory.TIMES, getSignatureLayout().getTextSize(),
                Font.NORMAL, new Color(0x00, 0x00, 0x00));
        pdfSignatureAppearance.setLayer2Font(layer2Font);
        pdfSignatureAppearance.setRender(PdfSignatureAppearance.SignatureRenderDescription);

        pdfSignatureAppearance.setVisibleSignature(getNextCertificatePosition(pdfReader, pdfCertificates), 1,
                null);

        pdfStamper.close(); // closes the file

        log.debug("File " + outputFile.getAbsolutePath() + " created and signed with " + reason);

        return blob;
    } catch (IOException e) {
        throw new SignException(e);
    } catch (DocumentException e) {
        // iText PDF stamping
        throw new SignException(e);
    } catch (IllegalArgumentException e) {
        if (String.valueOf(e.getMessage()).contains("PdfReader not opened with owner password")) {
            // iText PDF reading
            throw new SignException("PDF is password-protected");
        }
        throw new SignException(e);
    }
}