Example usage for java.security.cert X509Certificate getIssuerDN

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

Introduction

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

Prototype

public abstract Principal getIssuerDN();

Source Link

Document

Denigrated, replaced by #getIssuerX500Principal() .

Usage

From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java

private void showCertificate(X509Certificate certificate) {
    Map<String, String> dns = DNParser.parse(certificate.getSubjectDN());
    tracer.info(String.format("subject:             %s", dns.get(SinekartaDsObjectIdentifiers.dn_commonName)));
    tracer.info(String.format("country:             %s", dns.get(SinekartaDsObjectIdentifiers.dn_countryName)));
    tracer.info(String.format("organization:        %s",
            dns.get(SinekartaDsObjectIdentifiers.dn_organizationName)));
    tracer.info(String.format("organization unit:   %s",
            dns.get(SinekartaDsObjectIdentifiers.dn_organizationUnitName)));
    tracer.info(String.format("not before:          %s", formatDate(certificate.getNotBefore())));
    tracer.info(String.format("not after:           %s", formatDate(certificate.getNotAfter())));
    dns = DNParser.parse(certificate.getIssuerDN());
    tracer.info(String.format("issuer:              %s", dns.get(SinekartaDsObjectIdentifiers.dn_commonName)));
}

From source file:com.codedx.burp.security.InvalidCertificateDialogStrategy.java

@Override
public CertificateAcceptance checkAcceptance(Certificate genericCert, CertificateException certError) {
    if (genericCert instanceof X509Certificate && defaultHostVerifier instanceof DefaultHostnameVerifier) {
        X509Certificate cert = (X509Certificate) genericCert;
        DefaultHostnameVerifier verifier = (DefaultHostnameVerifier) defaultHostVerifier;

        JPanel message = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridwidth = 2;//from   w  ww  .j av  a  2  s .c  o m
        gbc.insets = new Insets(0, 0, 10, 0);
        gbc.anchor = GridBagConstraints.WEST;
        message.add(
                new JLabel("Unable to establish a secure connection because the certificate is not trusted"),
                gbc);

        gbc = new GridBagConstraints();
        gbc.gridy = 2;
        gbc.insets = new Insets(2, 0, 2, 0);
        gbc.anchor = GridBagConstraints.WEST;

        JLabel issuer = new JLabel("Issuer: ");
        Font defaultFont = issuer.getFont();
        Font bold = new Font(defaultFont.getName(), Font.BOLD, defaultFont.getSize());
        issuer.setFont(bold);

        message.add(issuer, gbc);
        gbc.gridx = 1;
        message.add(new JLabel(cert.getIssuerDN().toString()), gbc);

        try {
            JLabel fingerprint = new JLabel("Thumbprint: ");
            fingerprint.setFont(bold);
            gbc.gridx = 0;
            gbc.gridy += 1;
            message.add(fingerprint, gbc);

            gbc.gridx = 1;
            message.add(new JLabel(toHexString(getSHA1(cert.getEncoded()), " ")), gbc);
        } catch (CertificateEncodingException e) {
            // this shouldn't actually ever happen
        }

        try {
            verifier.verify(host, cert);
        } catch (SSLException e) {
            String cn = getCN(cert);

            JLabel mismatch = new JLabel("Host Mismatch: ");
            mismatch.setFont(bold);
            gbc.gridx = 0;
            gbc.gridy += 1;
            message.add(mismatch, gbc);

            String msg;
            if (cn != null) {
                msg = String.format("Expected '%s', but the certificate is for '%s'.", host, cn);
            } else {
                msg = e.getMessage();
            }

            gbc.gridx = 1;
            message.add(new JLabel(msg), gbc);
        }

        // Open the dialog, and return its result
        int choice = JOptionPane.showOptionDialog(burpExtender.getUiComponent(), message, dialogTitle,
                JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, dialogButtons, null);
        switch (choice) {
        case (0):
            return CertificateAcceptance.REJECT;
        case (1):
            return CertificateAcceptance.ACCEPT_TEMPORARILY;
        case (2):
            return CertificateAcceptance.ACCEPT_PERMANENTLY;
        }
    }
    return CertificateAcceptance.REJECT;
}

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//from   www  .  ja  va 2s.  co m
        Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug(" Certificate :" + cert.getType());
}

From source file:org.signserver.admin.gui.ViewCertificateFrame.java

private void viewCertificate(final X509Certificate certificate) {
    this.certificate = certificate;
    if (certificate == null) {
        fields = null;/*from   w ww  .  j a  v  a 2 s  . com*/

    } else {
        fields = new ArrayList<Field>();

        fields.add(new Field("Version", String.valueOf(certificate.getVersion())));
        fields.add(new Field("Serial Number", certificate.getSerialNumber().toString(16)));
        fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName())));
        fields.add(new Field("Issuer", String.valueOf(certificate.getIssuerDN())));
        fields.add(new Field("Validity Not Before", String.valueOf(certificate.getNotBefore())));
        fields.add(new Field("Validity Not After", String.valueOf(certificate.getNotAfter())));
        fields.add(new Field("Subject", String.valueOf(certificate.getSubjectDN())));
        fields.add(new Field("Subject Public Key Algorithm",
                String.valueOf(certificate.getPublicKey().getAlgorithm())));
        fields.add(new Field("Subject's Public Key",
                new String(Hex.encode(certificate.getPublicKey().getEncoded()))));
        if (certificate.getCriticalExtensionOIDs() != null) {
            for (String extensionOid : certificate.getCriticalExtensionOIDs()) {
                fields.add(new Field("Critical extension: " + extensionOid, "<Not supported yet>"));
            }
        }
        if (certificate.getNonCriticalExtensionOIDs() != null) {
            for (String extensionOid : certificate.getNonCriticalExtensionOIDs()) {
                fields.add(new Field("Non critical extension: " + extensionOid, "<Not supported yet>"));
            }
        }
        fields.add(new Field("Certificate Signature Algorithm", String.valueOf(certificate.getSigAlgName())));
        fields.add(
                new Field("Certificate Signature Value", new String(Hex.encode(certificate.getSignature()))));

        fieldsList.setModel(new AbstractListModel() {

            @Override
            public int getSize() {
                return fields.size();
            }

            @Override
            public Object getElementAt(int index) {
                return fields.get(index);
            }
        });
    }
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test builder with issuer certificate.
 * /* w ww. j av  a 2 s. c  om*/
 * @throws Exception
 */
@Test
public void testBuilderCertWithValidIssuer() throws GeneralSecurityException {
    // create issuer certificate
    populate(builder);
    builder.setSubject(ISSUER_NAME);
    builder.setIssuer(ISSUER_NAME);
    builder.setPublicKey(issuerKeyPair.getPublic());
    builder.setBasicConstraints(true);

    X509Certificate issuer = builder.build(issuerKeyPair.getPrivate());

    // perform basic validation.
    issuer.verify(issuerKeyPair.getPublic());

    // verify the basics
    assertEquals(issuer.getSerialNumber(), serial);
    assertEquals(issuer.getSubjectDN().getName(), ISSUER_NAME);
    assertEquals(issuer.getIssuerDN().getName(), ISSUER_NAME);
    assertEquals(issuer.getNotBefore(), notBefore.getTime());
    assertEquals(issuer.getNotAfter(), notAfter.getTime());
    // assertEquals(issuer.getPublicKey(), issuerKeyPair.getPublic());
    // FIXME: returns null

    builder.reset();

    // create subject certificate
    populate(builder);
    builder.setIssuer(issuer);

    X509Certificate cert = builder.build(keyPair.getPrivate());

    // perform basic validation.
    cert.verify(keyPair.getPublic());

    // verify the basics
    assertEquals(cert.getSerialNumber(), serial);
    assertEquals(cert.getSubjectDN().getName(), SUBJECT_NAME);
    assertEquals(cert.getIssuerDN().getName(), ISSUER_NAME);
    assertEquals(cert.getNotBefore(), notBefore.getTime());
    assertEquals(cert.getNotAfter(), notAfter.getTime());
    // assertEquals(cert.getPublicKey(), keyPair.getPublic()); FIXME:
    // returns null
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

protected void checkCRL(X509Certificate cert, CertificateRevocationLists crlsList,
        TrustedCertificates trustedCerts) throws ProxyPathValidatorException {
    if (crlsList == null) {
        return;//from   w  w w .j  a va2 s .c o m
    }

    logger.debug("checkCRLs: enter");
    // Should not happen, just a sanity check.
    if (trustedCerts == null) {
        String err = "Trusted certificates are null, cannot verify CRLs";
        logger.error(err);
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, null, err);
    }

    String issuerName = cert.getIssuerDN().getName();
    X509CRL crl = crlsList.getCrl(issuerName);
    if (crl == null) {
        logger.debug("No CRL for certificate");
        return;
    }

    // get CA cert for the CRL
    X509Certificate x509Cert = trustedCerts.getCertificate(issuerName);
    if (x509Cert == null) {
        // if there is no trusted certs from that CA, then
        // the chain cannot contain a cert from that CA,
        // which implies not checking this CRL should be fine.
        logger.debug("No trusted cert with this CA signature");
        return;
    }

    // validate CRL
    try {
        crl.verify(x509Cert.getPublicKey());
    } catch (Exception exp) {
        logger.error("CRL verification failed");
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, exp);
    }

    Date now = new Date();
    // check date validity of CRL
    if ((crl.getThisUpdate().before(now))
            || ((crl.getNextUpdate() != null) && (crl.getNextUpdate().after(now)))) {
        if (crl.isRevoked(cert)) {
            throw new ProxyPathValidatorException(ProxyPathValidatorException.REVOKED, cert,
                    "This cert " + cert.getSubjectDN().getName() + " is on a CRL");
        }
    }

    logger.debug("checkCRLs: exit");
}

From source file:com.evilisn.DAO.CertMapper.java

@Override
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
    Cert crt = new Cert();
    crt.setCertificate(resultSet.getString("certificate"));
    CertificateFactory fact = null;
    try {/*from w  w  w  .j  av a 2s. c om*/
        fact = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    X509Certificate x509cert = null;
    InputStream stream = new ByteArrayInputStream(crt.getCertificate().getBytes(StandardCharsets.UTF_8));
    try {
        x509cert = (X509Certificate) fact.generateCertificate(stream);
        crt.setClient_cert(x509cert);
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    crt.setResponder_uri(OCSP.getResponderURI(x509cert));
    X509Certificate issuerCert;
    if (!cached_issuers.containsKey(getIssuerCertURL(x509cert))) {
        //download and set the issuers.
        try {
            issuerCert = getX509Certificate(httpGetBin(getIssuerCertURL(x509cert), true));
            cached_issuers.put(getIssuerCertURL(x509cert), issuerCert);
            crt.setIssuer_cert(issuerCert);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        issuerCert = cached_issuers.get(getIssuerCertURL(x509cert));
        crt.setIssuer_cert(issuerCert);
    }

    Principal principal = x509cert.getIssuerDN();
    String issuerDn = principal.getName();
    crt.setIssuer_dn(issuerDn);
    return crt;
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Recupera todas las crls que tiene publicadas dentro del cerficicado.
 * <p>/*w w w .  j  a va 2 s.c om*/
 * Si el certificado es ancert el metodo obtiene las urls desde las que
 * descargarse las crls y se las descarga.
 * <p>
 * Si el certificado es FNMT recupera la ruta dentro del ldap desde la que
 * descargarse las crls.
 * <p>
 * Si el certificado es de Viavansi se conecta a las crls y se las descarga.
 * TODO: En el futuro cachear las crls.
 * 
 * @param certificadoX509
 * @return
 * @throws CRLException
 * @throws NoSuchProviderException
 * @throws CertificateException
 */
public List<X509CRL> getCRLs(X509Certificate certificadoX509)
        throws CRLException, CertificateException, NoSuchProviderException {

    // Intentamos recuperar las crls del certificado desde la cache, para
    // minimizar los acccesos.
    List<X509CRL> listCrlFromCache = CrlCache.getInstance().getCrlsFrom(certificadoX509);
    if (listCrlFromCache == null) {
        // Es necesaria la recuperacin de las CRLs
        List<X509CRL> listCRLs = new ArrayList<X509CRL>(0);
        // ********************************************************************************
        // si es un certiticado de la FNMT hay que acceder al ldap para
        // recuperar las crls.
        // TODO Separar la obtencin de CRLS creando Handler especializados
        // TODO Mejorar el control de errores
        if (certificadoX509.getIssuerDN().getName().contains(Constantes.FNMT_ISSUERDN)) {
            // es un certificado de la FNMT. el procesamiento es diferente
            // al
            // resto, es atacando a un LDAP o a un OCSP en funcion de la configuracion del server
            // Comprobamos que no tiene valores nulos.
            if (!isSomeFNMTValorNull()) {
                log.debug("El certificado es de la fbrica, lo validamos utilizando el LDAP");
                listCRLs = getCrlLDAPFNMT(certificadoX509);
            }
        } else {
            // Es un certificado de ANCERT , Camerfirma o de VIAVANSI con el punto de
            // distribucin correctamente indicado.
            listCRLs = getCrlsPuntoDistribucion(certificadoX509);
        }
        // Aadimos a Cache
        CrlCache.getInstance().addToCache(certificadoX509, listCRLs);

        return listCRLs;
    } else {
        log.debug("Existe una cache vlida de crls asociada al certificado actual.");
        return listCrlFromCache;
    }
}

From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java

protected KeyMap cacheKeys(KeyStore ks, KeyInfoManager keyInfoManager)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    KeyMap keys = new KeyMap();

    // load and cache the keys
    for (Entry<String, KeyInformation> keyEntry : keyInfoManager.getKeyInfo().entrySet()) {
        String keyAlias = keyEntry.getKey();

        KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias);
        String passwordStr = keyInfo != null ? keyInfo.getPassword() : null;

        // Null is an acceptable value (means no key)
        Key key = null;// w  w w  .  j a v a  2  s . com

        // Attempt to get the key
        key = ks.getKey(keyAlias, passwordStr == null ? null : passwordStr.toCharArray());
        if (key != null) {
            keys.setKey(keyAlias, key);
        }
        // Key loaded
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Retrieved key from keystore: \n" + "   Location: " + getKeyStoreParameters().getLocation()
                            + "\n" + "   Provider: " + getKeyStoreParameters().getProvider() + "\n"
                            + "   Type:     " + getKeyStoreParameters().getType() + "\n" + "   Alias:    "
                            + keyAlias + "\n" + "   Password?: " + (passwordStr != null));

            Certificate[] certs = ks.getCertificateChain(keyAlias);
            if (certs != null) {
                logger.debug("Certificate chain '" + keyAlias + "':");
                for (int c = 0; c < certs.length; c++) {
                    if (certs[c] instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) certs[c];
                        logger.debug(" Certificate " + (c + 1) + ":");
                        logger.debug("  Subject DN: " + cert.getSubjectDN());
                        logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        logger.debug("  Valid from: " + cert.getNotBefore());
                        logger.debug("  Valid until: " + cert.getNotAfter());
                        logger.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
        }
    }

    return keys;
}