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:edu.duke.cabig.c3pr.web.security.SecureWebServiceHandler.java

/**
 * @param cert/*from  w  w w. j  av  a2 s  .c  om*/
 * @param crypto
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws InvalidKeyException
 * @throws WSSecurityException
 */
private void checkCertificateValidity(X509Certificate cert, Crypto crypto)
        throws InvalidKeyException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException,
        SignatureException, WSSecurityException {
    //cert.checkValidity();

    String subjectdn = cert.getSubjectDN().getName();
    String issuerdn = cert.getIssuerDN().getName();
    if (subjectdn.equals(issuerdn)) {
        log.debug("This is a self-signed certificate. Verifying signature...");
        cert.verify(cert.getPublicKey());
    } else {
        X509Certificate signingcert = getIssuerCert(cert, crypto);
        if (signingcert != null) {
            checkCertificateValidity(signingcert, crypto);
            cert.verify(signingcert.getPublicKey());
        } else {
            log.warn(
                    "Unable to check the signature of the certificate, because the issuer's certificate is not found. Certificate: "
                            + cert);
        }
    }
}

From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/* w  ww  .j  ava 2s. co  m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreID != null) {
            KeyStore keystore = createKeyStore(this.keystoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        logger.debug("Certificate chain '" + alias + "':");
                        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());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keyPassword);
        }
        if (this.truststoreID != null) {
            KeyStore keystore = createKeyStore(this.truststoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    logger.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        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());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslctx = SSLContext.getInstance("SSL");
        sslctx.init(keymanagers, trustmanagers, null);
        return sslctx;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java

@Override
public X509Certificate getSigningCertificate() {

    LOG.info("SignerInformation " + signerInformation.getSID());
    Collection<X509Certificate> certs = getCertificates();
    for (X509Certificate cert : certs) {
        LOG.info("Test match for certificate " + cert.getSubjectDN().getName());
        if (signerInformation.getSID().match(cert)) {
            return cert;
        }/*from w  w  w .ja  v  a2s.  co m*/
    }

    return null;
}

From source file:nl.nn.adapterframework.webcontrol.action.ShowSecurityItems.java

private void addCertificateInfo(XmlBuilder certElem, final URL url, final String password, String keyStoreType,
        String prefix) {//from ww w  .  jav a  2  s . co m
    try {
        KeyStore keystore = KeyStore.getInstance(keyStoreType);
        keystore.load(url.openStream(), password != null ? password.toCharArray() : null);
        if (log.isInfoEnabled()) {
            Enumeration aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                XmlBuilder infoElem = new XmlBuilder("info");
                infoElem.setCdataValue(prefix + " '" + alias + "':");
                certElem.addSubElement(infoElem);
                Certificate trustedcert = keystore.getCertificate(alias);
                if (trustedcert != null && trustedcert instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) trustedcert;
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Subject DN: " + cert.getSubjectDN());
                    certElem.addSubElement(infoElem);
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Signature Algorithm: " + cert.getSigAlgName());
                    certElem.addSubElement(infoElem);
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Valid from: " + cert.getNotBefore());
                    certElem.addSubElement(infoElem);
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Valid until: " + cert.getNotAfter());
                    certElem.addSubElement(infoElem);
                    infoElem = new XmlBuilder("info");
                    infoElem.setCdataValue("  Issuer: " + cert.getIssuerDN());
                    certElem.addSubElement(infoElem);
                }
            }
        }
    } catch (Exception e) {
        XmlBuilder infoElem = new XmlBuilder("info");
        infoElem.setCdataValue("*** ERROR ***");
        certElem.addSubElement(infoElem);
    }
}

From source file:org.midonet.api.auth.vsphere.FingerprintTrustManager.java

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    Preconditions.checkArgument(chain != null && chain.length > 0);
    Preconditions.checkArgument(!StringUtils.isEmpty(authType));

    MessageDigest messageDigest;/*  w ww. ja va2s  .  c o  m*/
    try {
        messageDigest = MessageDigest.getInstance("SHA-1");
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException(e);
    }

    for (X509Certificate certificate : chain) {
        final byte[] rawCertificateFingerprint = messageDigest.digest(certificate.getEncoded());

        final List<String> hexCertificateFingerprint = new ArrayList<>();

        for (byte aByte : rawCertificateFingerprint) {
            hexCertificateFingerprint.add(String.format("%02X", aByte));
        }

        final String fullCertificateFingerprint = Joiner.on(":").join(hexCertificateFingerprint);

        log.debug(String.format("Checking fingerprint %s for certificate %s", fullCertificateFingerprint,
                certificate.getSubjectDN()));

        if (trustedFingerprint.equalsIgnoreCase(fullCertificateFingerprint)) {
            log.debug(String.format("Found a the trusted fingerprint %s " + "for certificate %s",
                    fullCertificateFingerprint, certificate.getSubjectDN()));
            return;
        }
    }

    throw new CertificateException("No trusted certificate found");
}

From source file:com.xwiki.authentication.sts.STSTokenValidator.java

/**
  * validateToken(SignableSAMLObject samlToken)
  * Validates Token from SAMLlObject - returns boolen
  * Validates Token - exitracting sertificate from samlToken.
  * And validates it. Returning true or false according on validation results.
  * @param samlToken SignableSAMLObject/*w  w w. j  a  v  a  2 s . c  o  m*/
  * @return boolean valid => true, not valid => false
  */
private static boolean validateToken(SignableSAMLObject samlToken)
        throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException,
        CertificateException, KeyException {

    // Validate XML structure
    samlToken.validate(true);

    Signature signature = samlToken.getSignature();
    X509Certificate certificate = certFromToken(samlToken);

    // Certificate data
    log.debug("certificate issuerDN: " + certificate.getIssuerDN());
    log.debug("certificate issuerUniqueID: " + certificate.getIssuerUniqueID());
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal());
    log.debug("certificate notBefore: " + certificate.getNotBefore());
    log.debug("certificate notAfter: " + certificate.getNotAfter());
    log.debug("certificate serialNumber: " + certificate.getSerialNumber());
    log.debug("certificate sigAlgName: " + certificate.getSigAlgName());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate signature: " + new String(certificate.getSignature()));
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal().toString());
    log.debug("certificate publicKey: " + certificate.getPublicKey());
    log.debug("certificate subjectDN: " + certificate.getSubjectDN());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate version: " + certificate.getVersion());

    BasicX509Credential cred = new BasicX509Credential();
    cred.setEntityCertificate(certificate);

    // Credential data
    cred.setEntityId(entityId);
    log.debug("cred entityId: " + cred.getEntityId());
    log.debug("cred usageType: " + cred.getUsageType());
    log.debug("cred credentalContextSet: " + cred.getCredentalContextSet());
    log.debug("cred hashCode: " + cred.hashCode());
    log.debug("cred privateKey: " + cred.getPrivateKey());
    log.debug("cred publicKey: " + cred.getPublicKey());
    log.debug("cred secretKey: " + cred.getSecretKey());
    log.debug("cred entityCertificateChain: " + cred.getEntityCertificateChain());

    ArrayList<Credential> trustedCredentials = new ArrayList<Credential>();
    trustedCredentials.add(cred);

    CollectionCredentialResolver credResolver = new CollectionCredentialResolver(trustedCredentials);
    KeyInfoCredentialResolver kiResolver = SecurityTestHelper.buildBasicInlineKeyInfoResolver();
    ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(entityId));

    Base64 decoder = new Base64();
    // In trace mode write certificate in the file
    if (log.isTraceEnabled()) {
        String certEncoded = new String(decoder.encode(certificate.getEncoded()));
        try {
            FileUtils.writeStringToFile(new File("/tmp/Certificate.cer"),
                    "-----BEGIN CERTIFICATE-----\n" + certEncoded + "\n-----END CERTIFICATE-----");
            log.trace("Certificate file was saved in: /tmp/Certificate.cer");
        } catch (IOException e1) {
            log.error(e1);
        }
    }
    return engine.validate(signature, criteriaSet);
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java

public static BasicOCSPResp generateBasicOCSPResp(OCSPCAServiceRequest serviceReq, String sigAlg,
        X509Certificate signerCert, PrivateKey signerKey, String provider, X509Certificate[] chain,
        int respIdType)
        throws NotSupportedException, OCSPException, NoSuchProviderException, IllegalArgumentException {
    BasicOCSPResp returnval = null;//from   w  w w .  j  av  a  2s .c  om
    BasicOCSPRespGenerator basicRes = null;
    basicRes = OCSPUtil.createOCSPResponse(serviceReq.getOCSPrequest(), signerCert, respIdType);
    ArrayList responses = serviceReq.getResponseList();
    if (responses != null) {
        Iterator iter = responses.iterator();
        while (iter.hasNext()) {
            OCSPResponseItem item = (OCSPResponseItem) iter.next();
            basicRes.addResponse(item.getCertID(), item.getCertStatus(), item.getThisUpdate(),
                    item.getNextUpdate(), null);
        }
    }
    X509Extensions exts = serviceReq.getExtensions();
    if (exts != null) {
        Enumeration oids = exts.oids();
        if (oids.hasMoreElements()) {
            basicRes.setResponseExtensions(exts);
        }
    }

    returnval = basicRes.generate(sigAlg, signerKey, chain, new Date(), provider);
    if (m_log.isDebugEnabled()) {
        m_log.debug("Signing OCSP response with OCSP signer cert: " + signerCert.getSubjectDN().getName());
        RespID respId = null;
        if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
            respId = new RespID(signerCert.getSubjectX500Principal());
        } else {
            respId = new RespID(signerCert.getPublicKey());
        }
        if (!returnval.getResponderId().equals(respId)) {
            m_log.error("Response responderId does not match signer certificate responderId!");
        }
        boolean verify = returnval.verify(signerCert.getPublicKey(), "BC");
        if (verify) {
            m_log.debug("The OCSP response is verifying.");
        } else {
            m_log.error("The response is NOT verifying!");
        }
    }
    return returnval;
}

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

/**
 * Recupero los puntos de distribucin//  w  w  w .j a va  2 s. c o  m
 * 
 * @param certificadoX509
 * @return
 */
private List<String> getCrlPuntosDeDistribucion(X509Certificate certificadoX509)
        throws CertificateParsingException {
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado: " + certificadoX509.getSubjectDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)

        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            if (certificadoX509.getSubjectDN().getName().equals(certificadoX509.getIssuerDN().getName())) {
                log.debug("El certificado es un certificado raiz: " + certificadoX509.getSubjectDN().getName());
            } else {
                log.warn("   El certificado NO tiene punto de distribucin de CRL : "
                        + certificadoX509.getSubjectDN().getName());
            }
            return Collections.emptyList();
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();
            // Map<String,String> propiedades= new HashMap<String,String>();
            List<String> urls = getDERValue(derObj2);
            return urls;
            /*
             * CertificadoHelper.getCurrentInstance().readPropiedadesOid(OID_CRLS,derObj2,propiedades);
             * if(log.isDebugEnabled())log.debug("Informacin sobre CRls del
             * certificado que ha sido recuperada: "+propiedades); // por
             * simplificar, aunque el certificado informe de varias crls que
             * utilizar. Solo trabajamos con la primera List listaCrls=new
             * ArrayList(1); listaCrls.add(propiedades.get(OID_CRLS));
             * return listaCrls;//listaCrls.addAll(getDERValue(derObj2))
             */}
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }
}

From source file:org.syncany.plugins.webdav.WebdavTransferManager.java

private ConnectionSocketFactory initSsl() throws Exception {
    TrustStrategy trustStrategy = new TrustStrategy() {
        @Override/*from   ww w .j  a  v  a 2s .c om*/
        public boolean isTrusted(X509Certificate[] certificateChain, String authType)
                throws CertificateException {
            logger.log(Level.INFO, "WebDAV: isTrusted(" + certificateChain.toString() + ", " + authType + ")");

            try {
                // First check if already in trust store, if so; okay!
                X509Certificate serverCertificate = certificateChain[0];

                for (int i = 0; i < certificateChain.length; i++) {
                    X509Certificate certificate = certificateChain[i];

                    logger.log(Level.FINE,
                            "WebDAV: Checking certificate validity: " + certificate.getSubjectDN().toString());
                    logger.log(Level.FINEST, "WebDAV:              Full certificate: " + certificate);

                    // Check validity
                    try {
                        certificate.checkValidity();
                    } catch (CertificateException e) {
                        logger.log(Level.FINE, "WebDAV: Certificate is NOT valid.", e);
                        return false;
                    }

                    logger.log(Level.FINE, "WebDAV: Checking is VALID.");

                    // Certificate found; we trust this, okay!
                    if (inTrustStore(certificate)) {
                        logger.log(Level.FINE, "WebDAV: Certificate found in trust store.");
                        return true;
                    }

                    // Certificate is new; continue ...
                    else {
                        logger.log(Level.FINE, "WebDAV: Certificate NOT found in trust store.");
                    }
                }

                // We we reach this code, none of the CAs are known in the trust store
                // So we ask the user if he/she wants to add the server certificate to the trust store  
                UserInteractionListener userInteractionListener = getSettings().getUserInteractionListener();

                if (userInteractionListener == null) {
                    throw new RuntimeException("pluginListener cannot be null!");
                }

                boolean userTrustsCertificate = userInteractionListener.onUserConfirm(
                        "Unknown SSL/TLS certificate", formatCertificate(serverCertificate),
                        "Do you want to trust this certificate?");

                if (!userTrustsCertificate) {
                    logger.log(Level.INFO, "WebDAV: User does not trust certificate. ABORTING.");
                    throw new RuntimeException("User does not trust certificate. ABORTING.");
                }

                logger.log(Level.INFO, "WebDAV: User trusts certificate. Adding to trust store.");
                addToTrustStore(serverCertificate);

                return true;
            } catch (KeyStoreException e) {
                logger.log(Level.SEVERE, "WebDAV: Key store exception.", e);
                return false;
            }
        }

        private boolean inTrustStore(X509Certificate certificate) throws KeyStoreException {
            String certAlias = getCertificateAlias(certificate);
            return UserConfig.getUserTrustStore().containsAlias(certAlias);
        }

        private void addToTrustStore(X509Certificate certificate) throws KeyStoreException {
            String certAlias = getCertificateAlias(certificate);
            UserConfig.getUserTrustStore().setCertificateEntry(certAlias, certificate);

            hasNewCertificates = true;
        }

        private String getCertificateAlias(X509Certificate certificate) {
            return StringUtil.toHex(certificate.getSignature());
        }
    };

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustStrategy).useTLS().build();

    return new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private void saveTrustedCertificate(X509Certificate cert, String alias) {
    KeyStore keyStore = loadKeyStore();
    try {//from   ww w.  j av a 2  s  . c  o m
        log.info("Installing trusted CA certificate {}", cert.getSubjectDN());
        keyStore.setCertificateEntry(alias, cert);
        saveKeyStore(keyStore);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error saving trusted certificate", e);
    }
}