Example usage for javax.security.auth.x500 X500Principal toString

List of usage examples for javax.security.auth.x500 X500Principal toString

Introduction

In this page you can find the example usage for javax.security.auth.x500 X500Principal toString.

Prototype

public String toString() 

Source Link

Document

Return a user-friendly string representation of this X500Principal .

Usage

From source file:be.fedict.eid.applet.service.impl.UserIdentifierUtil.java

/**
 * Gives back a unique user identifier given an X509 certificate.
 * /*from  w  ww  . ja  v  a  2s . co  m*/
 * @param signingCertificate
 * @return
 */
public static String getUserId(X509Certificate signingCertificate) {
    X500Principal userPrincipal = signingCertificate.getSubjectX500Principal();
    String name = userPrincipal.toString();
    int serialNumberBeginIdx = name.indexOf("SERIALNUMBER=");
    if (-1 == serialNumberBeginIdx) {
        throw new SecurityException("SERIALNUMBER not found in X509 CN");
    }
    int serialNumberValueBeginIdx = serialNumberBeginIdx + "SERIALNUMBER=".length();
    int serialNumberValueEndIdx = name.indexOf(",", serialNumberValueBeginIdx);
    if (-1 == serialNumberValueEndIdx) {
        serialNumberValueEndIdx = name.length();
    }
    String userId = name.substring(serialNumberValueBeginIdx, serialNumberValueEndIdx);
    return userId;
}

From source file:be.e_contract.mycarenet.certra.CertRAClient.java

public static String getSSIN(X509Certificate certificate) {
    X500Principal userPrincipal = certificate.getSubjectX500Principal();
    String name = userPrincipal.toString();
    int serialNumberBeginIdx = name.indexOf("SERIALNUMBER=");
    if (-1 == serialNumberBeginIdx) {
        throw new SecurityException("SERIALNUMBER not found in X509 CN");
    }//from ww  w  .  ja  v  a  2s .c  o m
    int serialNumberValueBeginIdx = serialNumberBeginIdx + "SERIALNUMBER=".length();
    int serialNumberValueEndIdx = name.indexOf(",", serialNumberValueBeginIdx);
    if (-1 == serialNumberValueEndIdx) {
        serialNumberValueEndIdx = name.length();
    }
    String userId = name.substring(serialNumberValueBeginIdx, serialNumberValueEndIdx);
    return userId;
}

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

/**
 * Returns the friendly String version of the X500Principal
 *//*from  w w  w  . j a  va 2s  . c o m*/
public static String getFriendly(X500Principal principal) {
    if (principal == null) {
        return null;
    }

    return principal.toString();
}

From source file:org.aevans.goat.net.SSLStrategyGetter.java

public static SchemeIOSessionStrategy getSchemeIOSessionStrategy() {
    DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(
            PublicSuffixMatcherLoader.getDefault());
    SchemeIOSessionStrategy sioss = new SchemeIOSessionStrategy() {

        @Override// w w w  .j  a v  a2 s  . co m
        public boolean isLayeringRequired() {
            return true;
        }

        @Override
        public IOSession upgrade(final HttpHost host, final IOSession iosession) throws IOException {

            SSLSetupHandler handler = new SSLSetupHandler() {

                @Override
                public void initalize(SSLEngine sslengine) throws SSLException {
                }

                @Override
                public void verify(IOSession iosession, SSLSession sslsession) throws SSLException {
                    if (!hostnameVerifier.verify(host.getHostName(), sslsession)) {
                        final java.security.cert.Certificate[] certs = sslsession.getPeerCertificates();
                        final X509Certificate x509 = (X509Certificate) certs[0];
                        final X500Principal x500Principal = x509.getSubjectX500Principal();
                        throw new SSLPeerUnverifiedException("Host name '" + host.getHostName()
                                + "' does not match " + "the certificate subject provided by the peer ("
                                + x500Principal.toString() + ")");
                    }
                }

            };
            SSLBufferManagementStrategy sslbm = new ReleasableSSLBufferManagementStrategy();
            SSLIOSession ssio = new SSLIOSession(iosession, SSLMode.CLIENT, host, SSLContexts.createDefault(),
                    handler, sslbm);
            iosession.setAttribute(SSLIOSession.SESSION_KEY, ssio);
            ssio.initialize();
            return ssio;
        }

    };

    return sioss;
}

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.eid.applet.beta.admin.AdministratorServiceBean.java

private String getUserId(X509Certificate adminCert) {
    X500Principal userPrincipal = adminCert.getSubjectX500Principal();
    String name = userPrincipal.toString();
    int serialNumberValueBeginIdx = name.indexOf("SERIALNUMBER=") + "SERIALNUMBER=".length();
    int serialNumberValueEndIdx = name.indexOf(",", serialNumberValueBeginIdx);
    if (-1 == serialNumberValueEndIdx) {
        serialNumberValueEndIdx = name.length();
    }//from w ww .  ja  va2  s .co  m
    String userId = name.substring(serialNumberValueBeginIdx, serialNumberValueEndIdx);
    return userId;
}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from   w w w.  ja v  a2 s.  c o  m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier;
        if (!hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:org.dcache.ftp.client.extended.GridFTPControlChannel.java

/**
 * Performs authentication with specified user credentials and
 * a specific username (assuming the user dn maps to the passed username).
 *
 * @throws IOException     on i/o error/*www .ja v a2s .co m*/
 * @throws ServerException on server refusal or faulty server behavior
 */
private DssContext authenticate(DssContextFactory factory, String expectedHostName)
        throws IOException, ServerException {
    DssContext context;
    try {
        try {
            Reply reply = inner.exchange(new Command("AUTH", "GSSAPI"));
            if (!Reply.isPositiveIntermediate(reply)) {
                throw ServerException.embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(reply),
                        "Server refused GSSAPI authentication.");
            }
        } catch (FTPReplyParseException rpe) {
            throw ServerException.embedFTPReplyParseException(rpe, "Received faulty reply to AUTH GSSAPI.");
        }

        context = factory.create(inner.getRemoteAddress(), inner.getLocalAddress());

        Reply reply;
        byte[] inToken = new byte[0];
        do {
            byte[] outToken = context.init(inToken);
            reply = inner.exchange(new Command("ADAT",
                    BaseEncoding.base64().encode(outToken != null ? outToken : new byte[0])));
            if (reply.getMessage().startsWith("ADAT=")) {
                inToken = BaseEncoding.base64().decode(reply.getMessage().substring(5));
            } else {
                inToken = new byte[0];
            }
        } while (Reply.isPositiveIntermediate(reply) && !context.isEstablished());

        if (!Reply.isPositiveCompletion(reply)) {
            throw ServerException.embedUnexpectedReplyCodeException(new UnexpectedReplyCodeException(reply),
                    "Server failed GSI handshake.");
        }

        if (inToken.length > 0 || !context.isEstablished()) {
            byte[] outToken = context.init(inToken);
            if (outToken != null || !context.isEstablished()) {
                throw new ServerException(ServerException.WRONG_PROTOCOL,
                        "Unexpected GSI handshake completion.");
            }
        }

        SSLSession session = ((SslEngineDssContext) context).getSSLSession();
        if (!this.hostnameVerifier.verify(expectedHostName, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + expectedHostName + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
    } catch (FTPReplyParseException e) {
        throw ServerException.embedFTPReplyParseException(e, "Received faulty reply to ADAT.");
    }
    return context;
}

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from  ww w.  j a  v  a2 s  .c  o  m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Secure session established");
            LOGGER.debug(" negotiated protocol: {}", session.getProtocol());
            LOGGER.debug(" negotiated cipher suite: {}", session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                LOGGER.debug(" peer principal: {}", peer);
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" peer alternative names: {}", altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                LOGGER.debug(" issuer principal: {}", issuer);
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    LOGGER.debug(" issuer alternative names: {}", altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (RuntimeException | IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            iox.addSuppressed(x);
        }
        throw iox;
    }
}