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:be.fedict.eid.idp.webapp.ProtocolExitServlet.java

private static String getGivenName(X509Certificate authnCertificate) {

    X500Principal subjectPrincipal = authnCertificate.getSubjectX500Principal();
    String subjectName = subjectPrincipal.toString();
    return getAttributeFromSubjectName(subjectName, "GIVENNAME");
}

From source file:be.fedict.eid.idp.webapp.ProtocolExitServlet.java

private static String getSurName(X509Certificate authnCertificate) {

    X500Principal subjectPrincipal = authnCertificate.getSubjectX500Principal();
    String subjectName = subjectPrincipal.toString();
    return getAttributeFromSubjectName(subjectName, "SURNAME");
}

From source file:be.fedict.trust.crl.CrlTrustLinker.java

/**
 * Checks the integrity of the given X509 CRL.
 * /*from  ww  w  .jav  a2 s  .c om*/
 * @param x509crl
 *            the X509 CRL to verify the integrity.
 * @param issuerCertificate
 *            the assumed issuer of the given X509 CRL.
 * @param validationDate
 *            the validate date.
 * @return <code>true</code> if integrity is OK, <code>false</code>
 *         otherwise.
 */
public static boolean checkCrlIntegrity(X509CRL x509crl, X509Certificate issuerCertificate,
        Date validationDate) {
    if (false == x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
        return false;
    }
    try {
        x509crl.verify(issuerCertificate.getPublicKey());
    } catch (Exception e) {
        return false;
    }
    Date thisUpdate = x509crl.getThisUpdate();
    LOG.debug("validation date: " + validationDate);
    LOG.debug("CRL this update: " + thisUpdate);
    if (thisUpdate.after(validationDate)) {
        LOG.warn("CRL too young");
        return false;
    }
    LOG.debug("CRL next update: " + x509crl.getNextUpdate());
    if (validationDate.after(x509crl.getNextUpdate())) {
        LOG.debug("CRL too old");
        return false;
    }

    // assert cRLSign KeyUsage bit
    if (null == issuerCertificate.getKeyUsage()) {
        LOG.debug("No KeyUsage extension for CRL issuing certificate");
        return false;
    }

    if (false == issuerCertificate.getKeyUsage()[6]) {
        LOG.debug("cRLSign bit not set for CRL issuing certificate");
        return false;
    }

    return true;
}

From source file:mitm.common.security.certificate.X509CertificateInspector.java

/**
 * Returns true if the certificate is self signed ie. subject == issuer.
 *///ww w. j a  v  a2s.c  o m
public static boolean isSelfSigned(X509Certificate certificate) {
    return certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal());
}

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }//from   w  ww .ja  v a  2 s  .co m
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

public static String opensslHash(X509Certificate cert) {
    try {/* w  w w  . j  av  a2s  . c o  m*/
        return openssl_X509_NAME_hash(cert.getSubjectX500Principal());
    } catch (NoSuchAlgorithmException e) {
        throw new Error("MD5 isn't available!", e);
    }
}

From source file:org.globus.gsi.trustmanager.TrustedCertPathFinder.java

private static X509Certificate checkCertificate(List<X509Certificate> trustedCertPath,
        X509Certificate x509Certificate, Certificate issuerCertificate) throws CertPathValidatorException {
    X509Certificate x509IssuerCertificate = (X509Certificate) issuerCertificate;

    // check that the next one is indeed issuer, normalizing to Globus DN format
    String issuerDN = CertificateUtil.toGlobusID(x509Certificate.getIssuerX500Principal());
    String issuerCertDN = CertificateUtil.toGlobusID(x509IssuerCertificate.getSubjectX500Principal());

    if (!(issuerDN.equals(issuerCertDN))) {
        throw new IllegalArgumentException("Incorrect certificate path, certificate in chain can only "
                + "be issuer of previous certificate");
    }/* ww w .  ja  v a2  s.  co  m*/

    // validate integrity of signature
    PublicKey publicKey = x509IssuerCertificate.getPublicKey();
    try {
        x509Certificate.verify(publicKey);
    } catch (CertificateException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    } catch (InvalidKeyException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    } catch (NoSuchProviderException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    } catch (SignatureException e) {
        throw new CertPathValidatorException(
                "Signature validation on the certificate " + x509Certificate.getSubjectDN(), e);
    }

    trustedCertPath.add(x509Certificate);
    return x509IssuerCertificate;
}

From source file:mitm.common.security.certificate.X509CertificateInspector.java

/**
 * Returns the subject DN in a friendly format
 * @param certificate//from w ww .jav  a2 s  . c  om
 * @return
 */
public static String getSubjectFriendly(X509Certificate certificate) {
    return X500PrincipalInspector.getFriendly(certificate.getSubjectX500Principal());
}

From source file:mitm.common.security.certificate.X509CertificateInspector.java

/**
 * Returns the subject DN in a canonical RFC2253 format
 * @param certificate/*from   w ww . j  a  v  a 2  s  .com*/
 * @return
 */
public static String getSubjectCanonical(X509Certificate certificate) {
    return X500PrincipalInspector.getCanonical(certificate.getSubjectX500Principal());
}

From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java

private static KeyStore createKeyStore(final URL[] urls, final String[] passwords)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null);//w  ww  .j  ava 2s  . co  m

    if (urls == null) {
        throw new IllegalArgumentException("Keystore urls may not be null");
    }

    if (passwords != null && passwords.length != urls.length) {
        throw new IllegalArgumentException("Urls and passwords arrays must have the same size");
    }

    LOG.debug("Initializing key store");

    for (int i = 0; i < urls.length; i++) {

        LOG.debug("Adding " + urls[i].toString() + " to internal keystore");
        KeyStore ks = KeyStore.getInstance("jks");
        InputStream is = null;
        try {
            is = urls[i].openStream();

            if (passwords == null) {
                ks.load(is, null);
            } else {
                ks.load(is, passwords[i] != null ? passwords[i].toCharArray() : null);
            }

            for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
                X509Certificate cert = (X509Certificate) ks.getCertificate(e.nextElement());
                keystore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
            }
        } catch (IOException e) {
            if (AuthSSLProtocolSocketFactory.setup.getParameter("debug").equalsIgnoreCase("true")) {
                System.out.println("Erro ao abrir URL: " + urls[i].toExternalForm());
            }
        } finally {
            if (is != null)
                is.close();
        }
    }
    return keystore;
}