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:at.gv.egiz.pdfas.lib.impl.signing.pdfbox.LTVEnabledPADESPDFBOXSigner.java

/**
 * Adds the "Certs" dictionary to DSS dictionary as specified in <a href=
 * "http://www.etsi.org/deliver/etsi_ts%5C102700_102799%5C10277804%5C01.01.02_60%5Cts_10277804v010102p.pdf">PAdES
 * ETSI TS 102 778-4 v1.1.2, Annex A, "LTV extensions"</a>.
 *
 * @param pdDocument/* w w w .  j  a  v a2  s  . c  om*/
 *            The pdf document (required; must not be {@code null}).
 * @param dssDictionary
 *            The DSS dictionary (required; must not be {@code null}).
 * @param certificates
 *            The certificates (required; must not be {@code null}).
 * @throws IOException
 *             In case there was an error adding a pdf stream to the document.
 * @throws CertificateEncodingException
 *             In case of an error encoding certificates.
 */
private void addDSSCerts(PDDocument pdDocument, COSDictionary dssDictionary,
        Iterable<X509Certificate> certificates) throws IOException, CertificateEncodingException {
    final COSName COSNAME_CERTS = COSName.getPDFName("Certs");
    COSArray certsArray = (COSArray) Objects.requireNonNull(dssDictionary).getDictionaryObject(COSNAME_CERTS);
    if (certsArray == null) {
        // add new "Certs" array
        log.trace("Adding new DSS/Certs dictionary.");
        // "An array of (indirect references to) streams, each containing one BER-encoded X.509 certificate (see RFC 5280 [7])"
        certsArray = new COSArray();
        dssDictionary.setItem(COSNAME_CERTS, certsArray);
    }
    certsArray.setNeedToBeUpdate(true);

    // add BER-encoded X.509 certificates
    log.trace("Adding certificates to DSS/Certs dictionary.");
    for (X509Certificate certificate : certificates) {
        log.trace("Adding certificate for subject: {}", certificate.getSubjectDN());
        try (InputStream in = new ByteArrayInputStream(certificate.getEncoded())) {
            PDStream pdStream = new PDStream(pdDocument, in);
            pdStream.addCompression();
            certsArray.add(pdStream);
        }
    }
}

From source file:org.sipfoundry.sipxconfig.cert.CertificateManagerImpl.java

String getIssuer(String authority) {
    String authCertText = getSecurityData(AUTHORITY_TABLE, CERT_COLUMN, authority);
    X509Certificate authCert = CertificateUtils.readCertificate(authCertText);
    return authCert.getSubjectDN().getName();
}

From source file:org.josso.auth.scheme.validation.CRLX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {//from  w w  w.java 2s  .  c  om
        URL crlUrl = null;
        if (_url != null) {
            crlUrl = new URL(_url);
            log.debug("Using the CRL server at: " + _url);
        } else {
            log.debug("Using the CRL server specified in the certificate.");
            System.setProperty("com.sun.security.enableCRLDP", "true");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // disable OCSP
        Security.setProperty("ocsp.enable", "false");

        // get a certificate revocation list
        if (crlUrl != null) {
            URLConnection connection = crlUrl.openConnection();
            connection.setDoInput(true);
            connection.setUseCaches(false);
            DataInputStream inStream = new DataInputStream(connection.getInputStream());
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            X509CRL crl = (X509CRL) cf.generateCRL(inStream);
            inStream.close();
            params.addCertStore(CertStore.getInstance("Collection",
                    new CollectionCertStoreParameters(Collections.singletonList(crl))));
        }

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:gov.nih.nci.cacisweb.action.SecureXDSNAVAction.java

@Override
public String input() throws Exception {
    log.debug("input() - START");
    secureXDSNAVRecepientList = new ArrayList<SecureXDSNAVModel>();

    String secureXDSNAVKeystoreLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_LOCATION);
    String secureXDSNAVKeystorePassword = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_PASSWORD);
    String propertyFileLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_CONFIG_FILE_LOCATION);

    CaCISUtil caCISUtil = new CaCISUtil();
    try {/*  w w w . j av a2  s  .c  o  m*/
        caCISUtil.isPropertyFileAndKeystoreInSync(propertyFileLocation, secureXDSNAVKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureXDSNAVKeystorePassword);
    } catch (PropFileAndKeystoreOutOfSyncException e) {
        log.error(e.getMessage());
        addActionError(e.getMessage());
    }

    try {
        KeyStore keystore = caCISUtil.getKeystore(secureXDSNAVKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureXDSNAVKeystorePassword);
        // List the aliases
        //            Enumeration<String> enumeration = keystore.aliases();            
        Properties configFile = new Properties();
        InputStream is = new FileInputStream(propertyFileLocation);
        configFile.load(is);
        is.close();
        Enumeration<Object> enumeration = configFile.keys();
        //            while (enumeration.hasMoreElements()) {
        //                String alias = (String) enumeration.nextElement();
        //                X509Certificate x509Certificate = (X509Certificate) keystore.getCertificate(alias);
        //                SecureXDSNAVModel secureXDSNAVModel = new SecureXDSNAVModel();
        //                secureXDSNAVModel.setCertificateAlias(alias);
        //                secureXDSNAVModel.setCertificateDN(x509Certificate.getSubjectDN().toString());
        //                secureXDSNAVRecepientList.add(secureXDSNAVModel);
        //                log.debug("Alias: " + alias + " DN: " + x509Certificate.getSubjectDN().getName());
        //            }            
        while (enumeration.hasMoreElements()) {
            String alias = (String) enumeration.nextElement();
            X509Certificate x509Certificate = (X509Certificate) keystore.getCertificate(alias);
            String distinguishedName = "";
            if (x509Certificate != null) {
                distinguishedName = x509Certificate.getSubjectDN().toString();
            }
            //              String distinguishedName = CaCISUtil.getPropertyFromPropertiesFile(propertyFileLocation, alias);
            SecureXDSNAVModel secureXDSNAVModel = new SecureXDSNAVModel();
            secureXDSNAVModel.setCertificateAlias(alias);
            secureXDSNAVModel.setCertificateDN(distinguishedName);
            secureXDSNAVRecepientList.add(secureXDSNAVModel);
            log.debug("Alias: " + alias + " DN: " + distinguishedName);
        }

        caCISUtil.releaseKeystore();
    } catch (KeystoreInstantiationException kie) {
        log.error(kie.getMessage());
        addActionError(getText("exception.keystoreInstantiation"));
        return ERROR;
    }
    log.debug("input() - END");
    return INPUT;
}

From source file:davmail.util.ClientCertificateTest.java

public void testWindowsSmartCard() {
    try {/*from ww w .ja v  a2s  .c om*/
        KeyStore ks = KeyStore.getInstance("Windows-MY");
        ks.load(null, null);
        java.util.Enumeration en = ks.aliases();

        while (en.hasMoreElements()) {
            String aliasKey = (String) en.nextElement();
            X509Certificate c = (X509Certificate) ks.getCertificate(aliasKey);
            System.out.println("---> alias : " + aliasKey + " " + c.getSubjectDN());

            //PrivateKey key = (PrivateKey) ks.getKey(aliasKey, "Passw0rd".toCharArray());
            Certificate[] chain = ks.getCertificateChain(aliasKey);
        }

    } catch (Exception ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:org.apache.cxf.ws.security.sts.provider.token.Saml1TokenProvider.java

private org.opensaml.saml1.core.Subject createSubjectSAML1(X509Certificate certificate) throws Exception {
    DefaultBootstrap.bootstrap();/*  w  w w  .  j  a  v a2 s  .c  om*/
    org.opensaml.saml1.core.NameIdentifier nameID = (new org.opensaml.saml1.core.impl.NameIdentifierBuilder())
            .buildObject();
    nameID.setNameIdentifier(certificate.getSubjectDN().getName());
    nameID.setFormat("urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName");
    org.opensaml.saml1.core.Subject subject = (new org.opensaml.saml1.core.impl.SubjectBuilder()).buildObject();
    subject.setNameIdentifier(nameID);
    org.opensaml.saml1.core.ConfirmationMethod confirmationMethod = (new org.opensaml.saml1.core.impl.ConfirmationMethodBuilder())
            .buildObject();
    confirmationMethod.setConfirmationMethod("Urn:oasis:names:tc:SAML:1.0:cm:holder-of-key");
    org.opensaml.saml1.core.SubjectConfirmation confirmation = (new org.opensaml.saml1.core.impl.SubjectConfirmationBuilder())
            .buildObject();
    confirmation.getConfirmationMethods().add(confirmationMethod);
    BasicX509Credential keyInfoCredential = new BasicX509Credential();
    keyInfoCredential.setEntityCertificate(certificate);
    X509KeyInfoGeneratorFactory kiFactory = new X509KeyInfoGeneratorFactory();
    kiFactory.setEmitPublicKeyValue(true);
    KeyInfo keyInfo = kiFactory.newInstance().generate(keyInfoCredential);
    confirmation.setKeyInfo(keyInfo);
    subject.setSubjectConfirmation(confirmation);
    return subject;
}

From source file:gov.nih.nci.cacisweb.action.SecureFTPAction.java

@Override
public String input() throws Exception {
    log.debug("input() - START");
    secureFTPRecepientList = new ArrayList<SecureFTPModel>();
    String secureFTPPropertyFileLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_PROPERTIES_FILE_LOCATION);
    String secureFTPKeystoreLocation = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation,
            CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_LOCATION_PROP_NAME));
    String secureFTPKeystorePassword = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation,
            CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_PASSWORD_PROP_NAME));

    CaCISUtil caCISUtil = new CaCISUtil();
    String propertyFileLocation = CaCISUtil
            .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_CONFIG_FILE_LOCATION);

    try {/*from  w  w  w  .  j a v  a 2s.  c o  m*/
        caCISUtil.isPropertyFileAndKeystoreInSync(propertyFileLocation, secureFTPKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword);
    } catch (PropFileAndKeystoreOutOfSyncException e) {
        if (!StringUtils.contains(e.getMessage(), "sftp")) {
            log.error(e.getMessage());
            addActionError(e.getMessage());
        }
    }

    try {
        KeyStore keystore = caCISUtil.getKeystore(secureFTPKeystoreLocation,
                CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword);
        // // List the aliases
        // Enumeration<String> enumeration = keystore.aliases();
        Properties configFile = new Properties();
        InputStream is = new FileInputStream(propertyFileLocation);
        configFile.load(is);
        is.close();
        Enumeration<Object> enumeration = configFile.keys();
        // while (enumeration.hasMoreElements()) {
        // String alias = (String) enumeration.nextElement();
        // X509Certificate x509Certificate = (X509Certificate) keystore.getCertificate(alias);
        // SecureFTPModel secureFTPModel = new SecureFTPModel();
        // secureFTPModel.setCertificateAlias(alias);
        // secureFTPModel.setCertificateDN(x509Certificate.getSubjectDN().toString());
        // secureFTPRecepientList.add(secureFTPModel);
        // log.debug("Alias: " + alias + " DN: " + x509Certificate.getSubjectDN().getName());
        // }
        while (enumeration.hasMoreElements()) {
            String alias = (String) enumeration.nextElement();
            X509Certificate x509Certificate = (X509Certificate) keystore.getCertificate(alias);
            String distinguishedName = "";
            if (x509Certificate != null) {
                distinguishedName = x509Certificate.getSubjectDN().toString();
            }
            SecureFTPModel secureFTPModel = new SecureFTPModel();
            secureFTPModel.setCertificateAlias(alias);
            secureFTPModel.setCertificateDN(distinguishedName);
            secureFTPRecepientList.add(secureFTPModel);
            log.debug("Alias: " + alias + " DN: " + distinguishedName);
        }

        caCISUtil.releaseKeystore();
    } catch (KeystoreInstantiationException kie) {
        log.error(kie.getMessage());
        addActionError(getText("exception.keystoreInstantiation"));
        return ERROR;
    }
    log.debug("input() - END");
    return INPUT;
}

From source file:org.apache.nifi.processors.email.smtp.SmtpConsumer.java

private Map<String, String> extractMessageAttributes() {
    final Map<String, String> attributes = new HashMap<>();
    final Certificate[] tlsPeerCertificates = context.getTlsPeerCertificates();
    if (tlsPeerCertificates != null) {
        for (int i = 0; i < tlsPeerCertificates.length; i++) {
            if (tlsPeerCertificates[i] instanceof X509Certificate) {
                X509Certificate x509Cert = (X509Certificate) tlsPeerCertificates[i];
                attributes.put("smtp.certificate." + i + ".serial", x509Cert.getSerialNumber().toString());
                attributes.put("smtp.certificate." + i + ".subjectName", x509Cert.getSubjectDN().getName());
            }//from  ww  w.  j av  a  2 s  .c o  m
        }
    }

    SocketAddress address = context.getRemoteAddress();
    if (address != null) {
        // will extract and format source address if available
        String strAddress = address instanceof InetSocketAddress
                ? ((InetSocketAddress) address).getHostString() + ":" + ((InetSocketAddress) address).getPort()
                : context.getRemoteAddress().toString();
        attributes.put("smtp.src", strAddress);
    }

    attributes.put("smtp.helo", context.getHelo());
    attributes.put("smtp.from", from);
    for (int i = 0; i < recipientList.size(); i++) {
        attributes.put("smtp.recipient." + i, recipientList.get(i));
    }
    attributes.put(CoreAttributes.MIME_TYPE.key(), "message/rfc822");
    return attributes;
}

From source file:org.josso.auth.scheme.validation.OCSPX509CertificateValidator.java

public void validate(X509Certificate certificate) throws X509CertificateValidationException {

    try {//from w  w w .  j a  va  2s .  co m
        if (_url != null) {
            log.debug("Using the OCSP server at: " + _url);
            Security.setProperty("ocsp.responderURL", _url);
        } else {
            log.debug("Using the OCSP server specified in the " + "Authority Info Access (AIA) extension "
                    + "of the certificate");
        }

        // configure the proxy
        if (_httpProxyHost != null && _httpProxyPort != null) {
            System.setProperty("http.proxyHost", _httpProxyHost);
            System.setProperty("http.proxyPort", _httpProxyPort);
        } else {
            System.clearProperty("http.proxyHost");
            System.clearProperty("http.proxyPort");
        }

        // get certificate path
        CertPath cp = generateCertificatePath(certificate);

        // get trust anchors
        Set<TrustAnchor> trustedCertsSet = generateTrustAnchors();

        // init PKIX parameters
        PKIXParameters params = new PKIXParameters(trustedCertsSet);

        // init cert store
        Set<X509Certificate> certSet = new HashSet<X509Certificate>();
        if (_ocspCert == null) {
            _ocspCert = getCertificate(_ocspResponderCertificateAlias);
        }
        if (_ocspCert != null) {
            certSet.add(_ocspCert);
            CertStoreParameters storeParams = new CollectionCertStoreParameters(certSet);
            CertStore store = CertStore.getInstance("Collection", storeParams);
            params.addCertStore(store);
            Security.setProperty("ocsp.responderCertSubjectName",
                    _ocspCert.getSubjectX500Principal().getName());
        }

        // activate certificate revocation checking
        params.setRevocationEnabled(true);

        // activate OCSP
        Security.setProperty("ocsp.enable", "true");

        // perform validation
        CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult cpvResult = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
        X509Certificate trustedCert = (X509Certificate) cpvResult.getTrustAnchor().getTrustedCert();

        if (trustedCert == null) {
            log.debug("Trsuted Cert = NULL");
        } else {
            log.debug("Trusted CA DN = " + trustedCert.getSubjectDN());
        }

    } catch (CertPathValidatorException e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    } catch (Exception e) {
        log.error(e, e);
        throw new X509CertificateValidationException(e);
    }
    log.debug("CERTIFICATE VALIDATION SUCCEEDED");
}

From source file:org.apache.xml.security.keys.storage.implementations.CertsInFilesystemDirectoryResolver.java

/**
 * Method readCertsFromHarddrive/*from w w  w .j av  a2  s  . c  o m*/
 *
 * @throws StorageResolverException
 */
private void readCertsFromHarddrive() throws StorageResolverException {

    File certDir = new File(this.merlinsCertificatesDir);
    List<String> al = new ArrayList<String>();
    String[] names = certDir.list();

    for (int i = 0; i < names.length; i++) {
        String currentFileName = names[i];

        if (currentFileName.endsWith(".crt")) {
            al.add(names[i]);
        }
    }

    CertificateFactory cf = null;

    try {
        cf = CertificateFactory.getInstance("X.509");
    } catch (CertificateException ex) {
        throw new StorageResolverException("empty", ex);
    }

    if (cf == null) {
        throw new StorageResolverException("empty");
    }

    for (int i = 0; i < al.size(); i++) {
        String filename = certDir.getAbsolutePath() + File.separator + (String) al.get(i);
        File file = new File(filename);
        boolean added = false;
        String dn = null;

        try {
            FileInputStream fis = new FileInputStream(file);
            X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);

            fis.close();

            //add to ArrayList
            cert.checkValidity();
            this.certs.add(cert);

            dn = cert.getSubjectDN().getName();
            added = true;
        } catch (FileNotFoundException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (IOException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateNotYetValidException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateExpiredException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        } catch (CertificateException ex) {
            if (log.isDebugEnabled()) {
                log.debug("Could not add certificate from file " + filename, ex);
            }
        }

        if (added && log.isDebugEnabled()) {
            log.debug("Added certificate: " + dn);
        }
    }
}