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.apache.nifi.registry.security.util.CertificateUtils.java

/**
 * Returns the DN extracted from the client certificate.
 *
 * If the client auth setting is WANT or NONE and a certificate is not present (and {@code respectClientAuth} is {@code true}), this method will return {@code null}.
 * If the client auth is NEED, it will throw a {@link CertificateException}.
 *
 * @param sslSocket the SSL Socket//from   w ww. j a  v a2s .co m
 * @return the extracted DN
 * @throws CertificateException if there is a problem parsing the certificate
 */
private static String extractPeerDNFromClientSSLSocket(SSLSocket sslSocket) throws CertificateException {
    String dn = null;

    /** The clientAuth value can be "need", "want", or "none"
     * A client must send client certificates for need, should for want, and will not for none.
     * This method should throw an exception if none are provided for need, return null if none are provided for want, and return null (without checking) for none.
     */

    ClientAuth clientAuth = getClientAuthStatus(sslSocket);
    logger.debug("SSL Socket client auth status: {}", clientAuth);

    if (clientAuth != ClientAuth.NONE) {
        try {
            final Certificate[] certChains = sslSocket.getSession().getPeerCertificates();
            if (certChains != null && certChains.length > 0) {
                X509Certificate x509Certificate = convertAbstractX509Certificate(certChains[0]);
                dn = x509Certificate.getSubjectDN().getName().trim();
                logger.debug("Extracted DN={} from client certificate", dn);
            }
        } catch (SSLPeerUnverifiedException e) {
            if (e.getMessage().equals(PEER_NOT_AUTHENTICATED_MSG)) {
                logger.error("The incoming request did not contain client certificates and thus the DN cannot"
                        + " be extracted. Check that the other endpoint is providing a complete client certificate chain");
            }
            if (clientAuth == ClientAuth.WANT) {
                logger.warn(
                        "Suppressing missing client certificate exception because client auth is set to 'want'");
                return dn;
            }
            throw new CertificateException(e);
        }
    }
    return dn;
}

From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java

public static KeyStore decodePEMTrustStore(final String pemContent, final String aliasPrefix)
        throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    Logger logger = LoggerFactory.getLogger(SSLUtils.class);

    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*  w  w  w . j  a  va2  s  .  co m*/

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    final List<String> lines = readLines(pemContent);

    final StringBuilder current = new StringBuilder();
    final List<String> entries = new ArrayList<String>();
    for (String line : lines) {
        if (line == null) {
            continue;
        }

        if (line.startsWith("-----BEGIN")) {
            current.setLength(0);
        } else if (line.startsWith("-----END")) {
            entries.add(current.toString());
        } else {
            current.append(line);
        }
    }

    logger.trace("Found {} entries to decode.", entries.size());

    int i = 0;
    for (final String entry : entries) {
        logger.trace("Decoding certificate info from:\n\n{}\n\n", entry);
        final byte[] data = decodeBase64(entry);

        final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data));
        X509Certificate cert = (X509Certificate) c;

        Set<String> aliases = new HashSet<String>();
        if (i < 1) {
            aliases.add(aliasPrefix);
        } else {
            aliases.add(aliasPrefix + i);
        }

        extractAliases(cert, aliases);

        KeyStore.TrustedCertificateEntry ksEntry = new KeyStore.TrustedCertificateEntry(cert);
        for (String alias : aliases) {
            ks.setEntry(alias, ksEntry, null);
            logger.trace("Storing trusted cert under alias: {}\n  with DN: {}", alias,
                    cert.getSubjectDN().getName());
        }

        logger.trace("Certificate added.");

        i++;
    }

    return ks;
}

From source file:de.zib.vold.security.FullDNExtractor.java

@Override
public Object extractPrincipal(final X509Certificate x509Certificate) {

    return x509Certificate.getSubjectDN().toString();
}

From source file:org.italiangrid.storm.webdav.authz.VOMSAuthenticationFilter.java

public Object extractPrincipal(X509Certificate cert) {

    return cert.getSubjectDN().getName();
}

From source file:org.apache.nifi.minifi.c2.security.authentication.X509AuthenticationToken.java

protected X509AuthenticationToken(X509Certificate[] x509Certificates,
        Collection<GrantedAuthority> grantedAuthorities) {
    super(grantedAuthorities);
    this.x509Certificates = Arrays.copyOf(x509Certificates, x509Certificates.length, X509Certificate[].class);
    X509Certificate x509Certificate = x509Certificates[0];
    this.subjectDn = x509Certificate.getSubjectDN().getName().trim();
}

From source file:grails.plugin.springsecurity.web.authentication.preauth.x509.ClosureX509PrincipalExtractor.java

public Object extractPrincipal(X509Certificate clientCert) {
    String subjectDN = clientCert.getSubjectDN().getName();

    log.debug("Subject DN is '{}'", subjectDN);

    Object username = closure.call(subjectDN);

    if (username == null) {
        throw new BadCredentialsException(messages.getMessage("SubjectDnX509PrincipalExtractor.noMatching",
                new Object[] { subjectDN }, "No matching pattern was found in subject DN: {}"));
    }/*from  ww w .  j av  a 2  s.  c o  m*/

    log.debug("Extracted Principal name is '{}'", username);

    return username;
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.AutoImportTrustManager.java

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    X509Certificate cert = chain[0];
    log.info("Importing certificate for " + cert.getSubjectDN());
    try {//from   w  w  w.j  av a2  s . co  m
        TrustStoreManager.getInstance().addCertificate(alias, cert);
    } catch (Exception ex) {
        log.error("Failed to import certificate", ex);
    }
}

From source file:org.wso2.carbon.hostobjects.sso.internal.util.Util.java

/**
 * This method validates the signature of the SAML Response.
 * @param resp SAML Response/* w  w  w .j  av a2  s . c o  m*/
 * @return true, if signature is valid.
 */
public static boolean validateSignature(Response resp, String keyStoreName, String keyStorePassword,
        String alias, int tenantId, String tenantDomain) {
    boolean isSigValid = false;
    try {
        KeyStore keyStore = null;
        java.security.cert.X509Certificate cert = null;
        if (tenantId != MultitenantConstants.SUPER_TENANT_ID) {
            // get an instance of the corresponding Key Store Manager instance
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(tenantDomain);
        } else {
            keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(new File(keyStoreName)), keyStorePassword.toCharArray());
            cert = (java.security.cert.X509Certificate) keyStore.getCertificate(alias);
        }
        if (log.isDebugEnabled()) {
            log.debug("Validating against " + cert.getSubjectDN().getName());
        }
        X509CredentialImpl credentialImpl = new X509CredentialImpl(cert);
        SignatureValidator signatureValidator = new SignatureValidator(credentialImpl);
        signatureValidator.validate(resp.getSignature());
        isSigValid = true;
        return isSigValid;
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Signature verification is failed for " + tenantDomain);
        }
        return isSigValid;
    }
}

From source file:org.ocsinventoryng.android.actions.CoolSSLSocketFactory.java

public CoolSSLSocketFactory(KeyStore truststore)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {

    super(truststore);

    TrustManager tm = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }/*from  ww w  .  j a  v a 2  s  .c  o m*/

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            for (X509Certificate aChain : chain) {
                Log.d("X509", aChain.getSubjectDN().toString());
            }
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    Log.d("X509", "CoolSSLSocketFactory");
    sslContext.init(null, new TrustManager[] { tm }, null);
    setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:net.jradius.radsec.SimpleTrustManager.java

public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    for (X509Certificate c : chain)
        System.err.println("Checking Client: " + c.getSubjectDN());
    trustManager.checkClientTrusted(chain, authType);
}