List of usage examples for java.security.cert X509Certificate getSubjectDN
public abstract Principal getSubjectDN();
From source file:org.votingsystem.web.ejb.SignatureBean.java
public void addCertAuthority(CertificateVS certificateVS) throws Exception { X509Certificate x509Cert = certificateVS.getX509Cert(); trustedCerts.add(x509Cert);//from w w w . j a v a 2 s . c o m trustedCertsHashMap.put(x509Cert.getSerialNumber().longValue(), certificateVS); trustAnchors.add(new TrustAnchor(x509Cert, null)); log.info("certificateVS.id: " + certificateVS.getId() + " - " + x509Cert.getSubjectDN() + " - num. trustedCerts: " + trustedCerts.size()); }
From source file:org.votingsystem.web.ejb.SignatureBean.java
public CertUtils.CertValidatorResultVS verifyUserCertificate(UserVS userVS) throws Exception { CertUtils.CertValidatorResultVS validatorResult = CertUtils.verifyCertificate(getTrustAnchors(), false, Arrays.asList(userVS.getCertificate())); X509Certificate certCaResult = validatorResult.getResult().getTrustAnchor().getTrustedCert(); userVS.setCertificateCA(getTrustedCertsHashMap().get(certCaResult.getSerialNumber().longValue())); log.log(Level.FINE, "verifyCertificate - user:" + userVS.getNif() + " cert issuer: " + certCaResult.getSubjectDN() + " - CA certificateVS.id : " + userVS.getCertificateCA().getId()); return validatorResult; }
From source file:com.fine47.http.SecureSocketFactory.java
private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(store); // Loading the CA certificate from store. Certificate rootca = store.getCertificate(alias); // Turn it to X509 format. InputStream is = new ByteArrayInputStream(rootca.getEncoded()); X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); ActivityHttpClient.silentCloseInputStream(is); if (null == x509ca) { throw new CertificateException("Found expired SSL certificate in this store: " + factoryId); }// w w w . j av a 2s. c om // Check the CA's validity. x509ca.checkValidity(); // Accepted CA is only the one installed in the store. acceptedIssuers = new X509Certificate[] { x509ca }; // Get the public key. publicKey = rootca.getPublicKey(); sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Exception error = null; if (null == chain || 0 == chain.length) { error = new CertificateException("Certificate chain is invalid"); } else if (null == authType || 0 == authType.length()) { error = new CertificateException("Authentication type is invalid"); } else try { for (X509Certificate cert : chain) { if (ActivityHttpClient.isDebugging()) { Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:"); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber()); Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion()); Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString()); Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString()); Log.d(ActivityHttpClient.LOG_TAG, "---------------------------"); } // Make sure that it hasn't expired. cert.checkValidity(); // Verify the certificate's chain. cert.verify(publicKey); } } catch (InvalidKeyException ex) { error = ex; } catch (NoSuchAlgorithmException ex) { error = ex; } catch (NoSuchProviderException ex) { error = ex; } catch (SignatureException ex) { error = ex; } if (null != error && ActivityHttpClient.isDebugging()) { Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error); throw new CertificateException(error); } } @Override public X509Certificate[] getAcceptedIssuers() { return acceptedIssuers; } } }, null); setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); }
From source file:com.stargame.ad.util.http.ssl.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/* ww w .ja va 2s.c o m*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (LogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { LogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; LogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":"); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (LogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; LogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); LogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:nl.nn.adapterframework.webcontrol.api.ShowConfigurationStatus.java
private ArrayList<Object> getCertificateInfo(final URL url, final String password, String keyStoreType, String prefix) {//from w ww .j ava 2 s .c om ArrayList<Object> certificateList = new ArrayList<Object>(); try { KeyStore keystore = KeyStore.getInstance(keyStoreType); keystore.load(url.openStream(), password != null ? password.toCharArray() : null); if (log.isInfoEnabled()) { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); ArrayList<Object> infoElem = new ArrayList<Object>(); infoElem.add(prefix + " '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; infoElem.add("Subject DN: " + cert.getSubjectDN()); infoElem.add("Signature Algorithm: " + cert.getSigAlgName()); infoElem.add("Valid from: " + cert.getNotBefore()); infoElem.add("Valid until: " + cert.getNotAfter()); infoElem.add("Issuer: " + cert.getIssuerDN()); } certificateList.add(infoElem); } } } catch (Exception e) { certificateList.add("*** ERROR ***"); } return certificateList; }
From source file:com.bitplan.rest.RestServerImpl.java
/** * check that the SSL Client Certificate is valid and return the checked * Principal//from w w w . j a va 2 s. c o m * * @param req */ protected Principal checkSSLClientCertificate(Request req) { X509Certificate clientCert = this.getCertificate(req); Principal result = null; if (clientCert != null) { Principal subjectDN = clientCert.getSubjectDN(); try { result = checkPrincipal(subjectDN); } catch (Exception e) { LOGGER.log(Level.SEVERE, "checkPrincipal failed with exception " + e.getMessage()); } } else { LOGGER.log(Level.SEVERE, "SSL Client certificate is missing for " + req.getRequestURI()); } return result; }
From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { try {/*from ww w.j ava2 s.c o m*/ if (!initialized.get()) { initializeServer(context); } } catch (Exception e) { context.yield(); throw new ProcessException("Failed to initialize the server", e); } final HttpRequestContainer container = containerQueue.poll(); if (container == null) { return; } final long start = System.nanoTime(); final HttpServletRequest request = container.getRequest(); FlowFile flowFile = session.create(); try { flowFile = session.importFrom(request.getInputStream(), flowFile); } catch (final IOException e) { getLogger().error("Failed to receive content from HTTP Request from {} due to {}", new Object[] { request.getRemoteAddr(), e }); session.remove(flowFile); return; } final String charset = request.getCharacterEncoding() == null ? context.getProperty(URL_CHARACTER_SET).getValue() : request.getCharacterEncoding(); final String contextIdentifier = UUID.randomUUID().toString(); final Map<String, String> attributes = new HashMap<>(); try { putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier); putAttribute(attributes, "mime.type", request.getContentType()); putAttribute(attributes, "http.servlet.path", request.getServletPath()); putAttribute(attributes, "http.context.path", request.getContextPath()); putAttribute(attributes, "http.method", request.getMethod()); putAttribute(attributes, "http.local.addr", request.getLocalAddr()); putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName()); final String queryString = request.getQueryString(); if (queryString != null) { putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset)); } putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost()); putAttribute(attributes, "http.remote.addr", request.getRemoteAddr()); putAttribute(attributes, "http.remote.user", request.getRemoteUser()); putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI()); putAttribute(attributes, "http.request.url", request.getRequestURL().toString()); putAttribute(attributes, "http.auth.type", request.getAuthType()); putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId()); final DispatcherType dispatcherType = request.getDispatcherType(); if (dispatcherType != null) { putAttribute(attributes, "http.dispatcher.type", dispatcherType.name()); } putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding()); putAttribute(attributes, "http.locale", request.getLocale()); putAttribute(attributes, "http.server.name", request.getServerName()); putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort()); final Enumeration<String> paramEnumeration = request.getParameterNames(); while (paramEnumeration.hasMoreElements()) { final String paramName = paramEnumeration.nextElement(); final String value = request.getParameter(paramName); attributes.put("http.param." + paramName, value); } final Cookie[] cookies = request.getCookies(); if (cookies != null) { for (final Cookie cookie : cookies) { final String name = cookie.getName(); final String cookiePrefix = "http.cookie." + name + "."; attributes.put(cookiePrefix + "value", cookie.getValue()); attributes.put(cookiePrefix + "domain", cookie.getDomain()); attributes.put(cookiePrefix + "path", cookie.getPath()); attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge())); attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion())); attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure())); } } if (queryString != null) { final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString); for (final String keyValueString : params) { final int indexOf = keyValueString.indexOf("="); if (indexOf < 0) { // no =, then it's just a key with no value attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), ""); } else { final String key = keyValueString.substring(0, indexOf); final String value; if (indexOf == keyValueString.length() - 1) { value = ""; } else { value = keyValueString.substring(indexOf + 1); } attributes.put("http.query.param." + URLDecoder.decode(key, charset), URLDecoder.decode(value, charset)); } } } } catch (final UnsupportedEncodingException uee) { throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated } final Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); final String headerValue = request.getHeader(headerName); putAttribute(attributes, "http.headers." + headerName, headerValue); } final Principal principal = request.getUserPrincipal(); if (principal != null) { putAttribute(attributes, "http.principal.name", principal.getName()); } final X509Certificate certs[] = (X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); final String subjectDn; if (certs != null && certs.length > 0) { final X509Certificate cert = certs[0]; subjectDn = cert.getSubjectDN().getName(); final String issuerDn = cert.getIssuerDN().getName(); putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn); putAttribute(attributes, "http.issuer.dn", issuerDn); } else { subjectDn = null; } flowFile = session.putAllAttributes(flowFile, attributes); final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP) .asControllerService(HttpContextMap.class); final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(), container.getContext()); if (!registered) { getLogger().warn( "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE", new Object[] { request.getRemoteAddr() }); try { container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode()); container.getResponse().flushBuffer(); container.getContext().complete(); } catch (final Exception e) { getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}", new Object[] { request.getRemoteAddr(), e }); } session.remove(flowFile); return; } final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes), "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn), receiveMillis); session.transfer(flowFile, REL_SUCCESS); getLogger().info("Transferring {} to 'success'; received from {}", new Object[] { flowFile, request.getRemoteAddr() }); }
From source file:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/* w w w . jav a2 s . com*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (AbLogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":"); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (AbLogUtil.D) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Subject DN: " + cert.getSubjectDN()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Signature Algorithm: " + cert.getSigAlgName()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid from: " + cert.getNotBefore()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Valid until: " + cert.getNotAfter()); AbLogUtil.d(AuthSSLProtocolSocketFactory.class, " Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage()); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java
/** * Verify that cached results are consistent. It's a strong indication that * someone has been screwing with the database if the values are * inconsistent. This is computationally expensive but the cost of a * corrupted database is far worse./*from w w w.j a va 2 s . c om*/ * * @param entity * @param cert */ public void validate(Entity entity, X509Certificate cert) throws CertificateException { if (!cert.getSerialNumber().equals(entity.getProperty(SERIAL_NUMBER))) { throw new CertificateException("serial number did not match"); } if (!cert.getIssuerDN().equals(entity.getProperty(ISSUER_DN))) { throw new CertificateException("issuer dn did not match"); } if (!cert.getSubjectDN().equals(entity.getProperty(SUBJECT_DN))) { throw new CertificateException("subject dn did not match"); } if (!cert.getNotBefore().equals(entity.getProperty(NOT_BEFORE))) { throw new CertificateException("notBefore did not match"); } if (!cert.getNotAfter().equals(entity.getProperty(NOT_AFTER))) { throw new CertificateException("notAfter did not match"); } if (!x509CertUtil.getName(cert).equals(entity.getProperty(COMMON_NAME))) { throw new CertificateException("common name did not match"); } if (!x509CertUtil.getFingerprint(cert).equals(entity.getProperty(FINGERPRINT))) { throw new CertificateException("cached fingerprints did not match"); } if (!x509CertUtil.getCertificateHash(cert).equals(entity.getProperty(CERT_HASH))) { throw new CertificateException("cached certificate hash did not match"); } if (!x509CertUtil.getIHash(cert).equals(entity.getProperty(ISSUER_HASH))) { throw new CertificateException("cached issuer hash did not match"); } if (!x509CertUtil.getSHash(cert).equals(entity.getProperty(SUBJECT_HASH))) { throw new CertificateException("cached subject hash did not match"); } if (!x509CertUtil.getAkidHash(cert).equals(entity.getProperty(AKID_HASH))) { throw new CertificateException("cached AKID hash did not match"); } if (!x509CertUtil.getSkidHash(cert).equals(entity.getProperty(SKID_HASH))) { throw new CertificateException("cached SKID hash did not match"); } }