public X509CertificateShortInfo(String alias, X509Certificate cert) { this.alias = alias; if (cert.getIssuerDN() != null) issuer = cert.getIssuerDN().getName(); if (cert.getSubjectDN() != null) subject = cert.getSubjectDN().getName(); algorithm = cert.getSigAlgName(); notBeforeDatetime = cert.getNotBefore(); notAfterDatetime = cert.getNotAfter(); updateViewStyle(); }
// 颁发证书 public static MadCertDo issueClientCert( long serialNo, String alias, String cn, String email, String title, Map<String, String> exts, char[] pwd) throws Exception { X500Name subject = X500NameUtil.createClass3EndPrincipal(cn, email, title); KeyPair caKeyPair = CaCertLoader.getClass3CaKeyPair(); KeyPair endKeyPair = KeyPairUtil.generateRSAKeyPair(); X509Certificate endCert = getIns().createClass3EndCert(serialNo, subject, exts, endKeyPair, caKeyPair); MadCertDo madCertDo = new MadCertDo(); madCertDo.setSerialNumber(serialNo); madCertDo.setNotBefore(endCert.getNotBefore()); madCertDo.setNotAfter(endCert.getNotAfter()); madCertDo.setIssuerDN(endCert.getIssuerDN().toString()); madCertDo.setSubjectDN(endCert.getSubjectDN().toString()); madCertDo.setKeyFile(PKCSTransformer.getKeyFileString(endKeyPair.getPrivate(), pwd)); madCertDo.setKeyPwd(String.valueOf(pwd)); return madCertDo; }
private void parseCert() { try { FileInputStream fis = new FileInputStream("e:\\rongyifu.der"); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate c = (X509Certificate) cf.generateCertificate(fis); System.out.println("Certficate for " + c.getSubjectDN().getName()); System.out.println("Generated with " + c.getSigAlgName()); System.out.println("== " + c.getSubjectDN().toString()); String publicKey = Base64.encode(c.getPublicKey().getEncoded()); System.out.println("publicKey=" + publicKey); // Map<String, String> map = parseSubjectDN(c.getSubjectDN().toString()); // System.out.println("map: "+map); // String notBefore =c.getNotBefore().toString();//得到开始有效日期 // String notAfter = c.getNotAfter().toString();//得到截止日期 String serialNumber = c.getSerialNumber().toString(16); // 得到序列号 String dn = c.getIssuerDN().getName(); // 得到发行者名 String sigAlgName = c.getSigAlgName(); // 得到签名算法 String algorithm = c.getPublicKey().getAlgorithm(); // 得到公钥算法 SimpleDateFormat intSDF = new SimpleDateFormat("yyyyMMdd"); System.out.println("notBefore=" + intSDF.format(c.getNotBefore())); System.out.println("notAfter=" + intSDF.format(c.getNotAfter())); System.out.println("serialNumber=" + serialNumber); System.out.println("dn=" + dn); System.out.println("sigAlgName=" + sigAlgName); System.out.println("algorithm=" + algorithm); fis.close(); } catch (Exception ex) { ex.printStackTrace(); } }
@Override public Component preview() { final Label commonNameLabel = new Label("certCommonName", new Model<String>()); final ByteArrayInputStream certificateStream = new ByteArrayInputStream(uploadedBytes); try { final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(certificateStream); final StringBuilder commonNameBuilder = new StringBuilder("cn="); final LdapName ldapName = new LdapName(certificate.getIssuerDN().getName()); for (Rdn rdn : ldapName.getRdns()) { if ("CN".equalsIgnoreCase(rdn.getType())) { commonNameBuilder.append( rdn.getValue() == null ? StringUtils.EMPTY : rdn.getValue().toString()); } } commonNameLabel.setDefaultModelObject(commonNameBuilder.toString()); } catch (Exception e) { LOG.error("Error evaluating certificate file", e); throw new IllegalArgumentException("Error evaluating certificate file", e); } finally { IOUtils.closeQuietly(certificateStream); } return this.add(commonNameLabel); }
public String getAliasFromCertificate(Certificate cer) throws KeyStoreException { X509Certificate xcer = (X509Certificate) cer, auxCer = null; String auxAlias = null; Enumeration<String> e = _mscapi.aliases(); while (e.hasMoreElements()) { auxAlias = (String) e.nextElement(); auxCer = (X509Certificate) _mscapi.getCertificate(auxAlias); if ((auxCer.getIssuerDN().equals(xcer.getIssuerDN())) && (auxCer.getSerialNumber().equals(xcer.getSerialNumber()))) { return auxAlias; } } return null; }
public void printCertificates() { System.out.println("Server sent " + tm.chain.length + " certificate(s):"); for (int i = 0; i < tm.chain.length; i++) { X509Certificate cert = tm.chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); System.out.println(); } }
static void dumpChain(Certificate[] chain) { for (int i = 0; i < chain.length; i++) { Certificate cert = chain[i]; if (cert instanceof X509Certificate) { X509Certificate x509 = (X509Certificate) chain[i]; System.err.println("subject: " + x509.getSubjectDN()); System.err.println("issuer: " + x509.getIssuerDN()); } } }
@Test public void testSelfSignedCertificate() throws Exception { KeyStore keystore = createKeyStore(); KeyStoreUtil.updateWithSelfSignedServerCertificate(keystore); X509Certificate cert = (X509Certificate) keystore.getCertificate("jolokia-agent"); assertNotNull(cert); assertEquals( cert.getSubjectDN().getName(), "CN=Jolokia Agent " + Version.getAgentVersion() + ", OU=JVM, O=jolokia.org, L=Pegnitz, ST=Franconia, C=DE"); assertEquals(cert.getSubjectDN(), cert.getIssuerDN()); }
private void validateChain(List<Certificate> chain, Certificate cert) { List<Certificate> certs = new ArrayList<Certificate>(); List<Certificate> root = new ArrayList<Certificate>(); Set<TrustAnchor> anchors = new HashSet<TrustAnchor>(); certs.add(cert); // adding for self signed certs certs.addAll(chain); for (Certificate c : certs) { if (!(c instanceof X509Certificate)) throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate"); X509Certificate xCert = (X509Certificate) c; Principal subject = xCert.getSubjectDN(); Principal issuer = xCert.getIssuerDN(); if (issuer != null && subject.equals(issuer)) { root.add(c); anchors.add(new TrustAnchor(xCert, null)); } } if (root.size() == 0) throw new IllegalArgumentException("No root certificates found for certificate chain", null); X509CertSelector target = new X509CertSelector(); target.setCertificate((X509Certificate) cert); PKIXBuilderParameters params = null; try { params = new PKIXBuilderParameters(anchors, target); params.setRevocationEnabled(false); params.addCertStore( CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs))); CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC"); builder.build(params); } catch (InvalidAlgorithmParameterException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (CertPathBuilderException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid certificate chain", e); } catch (NoSuchProviderException e) { throw new CloudRuntimeException("No provider for certificate validation", e); } }
private void certDetails(StringBuffer si, X509Certificate c) { SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd"); si.append("\n"); si.append(c.getSubjectDN().toString()); si.append("\n"); si.append(validityDateFormater.format(c.getNotBefore())); si.append(" - "); si.append(validityDateFormater.format(c.getNotAfter())); si.append("\nSHA-256: "); si.append(certHash(c, "SHA-256")); si.append("\nSHA-1: "); si.append(certHash(c, "SHA-1")); si.append("\nSigned by: "); si.append(c.getIssuerDN().toString()); si.append("\n"); }
/* * Returns the list of root certificates * The list of certificates we received is an array of certificates * we have to determine * 1) how many chain do we have (a chain stops when verifier of a cert is * not the signer of the next cert in the list * 2) build a cert with the leaf signer and the root verifier for each chain */ public CertificatePair[] getRootCertificates() { if (rootCertificates == null) { rootCertificates = new CertificatePair[0]; List rootCertificatesList = new ArrayList(); if (certificates != null && certificates.size() > 0) { Iterator iter = certificates.iterator(); while (iter.hasNext()) { Certificate[] certs = (Certificate[]) iter.next(); if (certs != null && certs.length > 0) { CertificatePair pair = new CertificatePair(); pair.setIssuer(certs[0]); for (int i = 0; i < certs.length - 1; i++) { X509Certificate x509certRoot = (X509Certificate) certs[i]; X509Certificate x509certIssuer = (X509Certificate) certs[i + 1]; if (!x509certRoot.getIssuerDN().equals(x509certIssuer.getSubjectDN())) { pair.setRoot(x509certRoot); if (!rootCertificatesList.contains(pair)) { rootCertificatesList.add(pair); } pair = new CertificatePair(); pair.setIssuer(x509certIssuer); } } // add the latest one if (pair != null) { pair.setRoot(certs[certs.length - 1]); if (!rootCertificatesList.contains(pair)) { rootCertificatesList.add(pair); } } } } } if (rootCertificatesList.size() > 0) { rootCertificates = new CertificatePair[rootCertificatesList.size()]; rootCertificatesList.toArray(rootCertificates); } } return rootCertificates; }
private X509Certificate readCertificate(String certPath) { try { FileInputStream fr = new FileInputStream(certPath); CertificateFactory cf = CertificateFactory.getInstance("X509"); X509Certificate crt = (X509Certificate) cf.generateCertificate(fr); logger.info("Read certificate:"); logger.info("\tCertificate for: " + crt.getSubjectDN()); logger.info("\tCertificate issued by: " + crt.getIssuerDN()); logger.info("\tCertificate is valid from " + crt.getNotBefore() + " to " + crt.getNotAfter()); logger.info("\tCertificate SN# " + crt.getSerialNumber()); logger.info("\tGenerated with " + crt.getSigAlgName()); return crt; } catch (Exception e) { e.printStackTrace(); } return null; }
/** * Checks certification path by IssuerX500Principal keyed in CAroot<br> * <br> * Risale il certification path attraverso IssuerX500Principal chiave in CAroot * * @return true: if certification path is valid */ public boolean getPathValid() { isPathValid = true; X509Certificate certChild = cert; X509Certificate certParent = null; while (!certChild.getIssuerDN().equals(certChild.getSubjectDN())) { // finche' la CA non è autofirmata try { certParent = CAroot.getCACertificate(certChild.getIssuerX500Principal()); } catch (GeneralSecurityException ex) { // la CA non è presente nella root isPathValid = false; return isPathValid; } certChild = certParent; } ; return isPathValid; }
@Override public MetadataObject resolve(X509Certificate attestationCertificate) { String issuer = attestationCertificate.getIssuerDN().getName(); for (X509Certificate cert : certs.get(issuer)) { try { attestationCertificate.verify(cert.getPublicKey()); return metadata.get(cert); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (NoSuchProviderException e) { e.printStackTrace(); } catch (SignatureException e) { e.printStackTrace(); } } return null; }
private String certChainMessage(final X509Certificate[] chain, CertificateException cause) { Throwable e = cause; Log.d(TAG, "certChainMessage for " + e); StringBuffer si = new StringBuffer(); if (e.getCause() != null) { e = e.getCause(); si.append(e.getLocalizedMessage()); // si.append("\n"); } for (X509Certificate c : chain) { si.append("\n\n"); si.append(c.getSubjectDN().toString()); si.append("\nMD5: "); si.append(certHash(c, "MD5")); si.append("\nSHA1: "); si.append(certHash(c, "SHA-1")); si.append("\nSigned by: "); si.append(c.getIssuerDN().toString()); } return si.toString(); }
private void verify(X509Certificate[] certs, String authType) throws CertificateException { final int len = certs.length; for (int i = 0; i < len; i++) { final X509Certificate currentX509Cert = certs[i]; try { if (i == len - 1) { if (currentX509Cert.getSubjectDN().equals(currentX509Cert.getIssuerDN())) currentX509Cert.verify(currentX509Cert.getPublicKey()); } else { final X509Certificate nextX509Cert = certs[i + 1]; currentX509Cert.verify(nextX509Cert.getPublicKey()); } } catch (final Exception e) { final CertificateException ce = new ECFCertificateException( "Certificate chain is not valid", certs, authType); // $NON-NLS-1$ ce.initCause(e); throw ce; } } }
/* * Initializes the signerInfo and the VerifierInfo from the Certificate Pair */ private void initializeCertificates() { X509Certificate certRoot = null; X509Certificate certIssuer = null; CertificatePair trustedCertificate; if (getFoundCertificate() == null) { CertificatePair[] certs = getRootCertificates(); if (certs.length == 0) return; trustedCertificate = certs[0]; } else { trustedCertificate = getFoundCertificate(); } certRoot = (X509Certificate) trustedCertificate.getRoot(); certIssuer = (X509Certificate) trustedCertificate.getIssuer(); StringBuffer strb = new StringBuffer(); strb.append(issuerString(certIssuer.getSubjectDN())); strb.append("\r\n"); // $NON-NLS-1$ strb.append( NLS.bind( Messages.JarVerificationResult_ValidBetween, (new String[] { dateString(certIssuer.getNotBefore()), dateString(certIssuer.getNotAfter()) }))); strb.append(checkValidity(certIssuer)); signerInfo = strb.toString(); if (certIssuer != null && !certIssuer.equals(certRoot)) { strb = new StringBuffer(); strb.append(issuerString(certIssuer.getIssuerDN())); strb.append("\r\n"); // $NON-NLS-1$ strb.append( NLS.bind( Messages.JarVerificationResult_ValidBetween, (new String[] { dateString(certRoot.getNotBefore()), dateString(certRoot.getNotAfter()) }))); strb.append(checkValidity(certRoot)); verifierInfo = strb.toString(); } }
private void logKeyStore(KeyStore store) throws KeyStoreException { LOG.trace("Certificates count: " + store.size()); Enumeration aliases = store.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = store.getCertificateChain(alias); if (certs != null) { LOG.debug("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; LOG.trace(" Certificate " + (c + 1) + ":"); LOG.trace(" Subject DN: " + cert.getSubjectDN()); LOG.trace(" Signature Algorithm: " + cert.getSigAlgName()); LOG.trace(" Valid from: " + cert.getNotBefore()); LOG.trace(" Valid until: " + cert.getNotAfter()); LOG.trace(" Issuer: " + cert.getIssuerDN()); } } } } }
public static String extractIssuerAliasName(X509Certificate paramX509Certificate) { String str1 = ResourceManager.getMessage("config.unknownIssuer"); try { Principal localPrincipal = paramX509Certificate.getIssuerDN(); String str2 = localPrincipal.getName(); str1 = extractFromQuote(str2, "CN="); if (str1 == null) { String str3 = extractFromQuote(str2, "O="); String str4 = extractFromQuote(str2, "OU="); if ((str3 != null) || (str4 != null)) { MessageFormat localMessageFormat = new MessageFormat(ResourceManager.getMessage("config.certShowOOU")); Object[] arrayOfObject = {str3, str4}; if (str3 == null) arrayOfObject[0] = ""; if (str4 == null) arrayOfObject[1] = ""; str1 = localMessageFormat.format(arrayOfObject); } } if (str1 == null) str1 = ResourceManager.getMessage("config.unknownIssuer"); } catch (Exception localException) { } return str1; }
/** * Encodes the provided <tt>PkiMessage</tt> into a PKCS #7 <tt>signedData</tt>. * * @param message the <tt>PkiMessage</tt> to encode. * @return the encoded <tt>signedData</tt> * @throws MessageEncodingException if there is a problem encoding the <tt>PkiMessage</tt> */ public CMSSignedData encode(PkiMessage<?> message) throws MessageEncodingException { LOGGER.debug("Encoding pkiMessage"); LOGGER.debug("Encoding message: {}", message); CMSProcessable content = getContent(message); LOGGER.debug( "Signing pkiMessage using key belonging to [issuer={}; serial={}]", signerId.getIssuerDN(), signerId.getSerialNumber()); try { CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); generator.addSignerInfoGenerator(getSignerInfo(message)); generator.addCertificates(getCertificates()); LOGGER.debug("Signing {} content", content); CMSSignedData pkiMessage = generator.generate(DATA, content, true, (Provider) null, true); LOGGER.debug("Finished encoding pkiMessage"); return pkiMessage; } catch (CMSException e) { throw new MessageEncodingException(e); } catch (Exception e) { throw new MessageEncodingException(e); } }
@Override public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException { try { 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()); if (request.getQueryString() != null) { putAttribute( attributes, "http.query.string", URLDecoder.decode(request.getQueryString(), 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()); if (request.getDispatcherType() != null) { putAttribute(attributes, "http.dispatcher.type", request.getDispatcherType().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())); } } final String queryString = request.getQueryString(); 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()}); }
@Override public void execute() throws BuildException { try { if (url == null) { throw new BuildException("No url attribute"); } URL target; try { target = new URL(url); } catch (MalformedURLException e) { throw new BuildException("Bad URL " + url, e); } if (!certificateFile.exists()) { throw new BuildException("Missing File " + certificateFile); } String host = target.getHost(); // set the port, defaulting to 443 if not set int port = target.getPort(); if (port == -1) { port = 443; } char[] passphraseArray; passphraseArray = (passphrase != null) ? passphrase.toCharArray() : null; log( "Loading KeyStore " + certificateFile + " with " + (passphraseArray == null ? "null" : ("" + passphrase.length() + " char")) + " passphrase "); InputStream in = new FileInputStream(certificateFile); KeyStore ks; try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphraseArray); } finally { in.close(); } SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] {tm}, null); SSLSocketFactory factory = context.getSocketFactory(); log("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(timeout); try { log("Starting SSL handshake..."); socket.startHandshake(); socket.close(); log("No errors, certificate is already trusted"); } catch (SSLException e) { log("server is not yet trusted", e, Project.MSG_INFO); } X509Certificate[] chain = tm.chain; if (chain == null) { log("Could not obtain server certificate chain"); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); log("Server sent " + chain.length + " certificate(s):"); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; log(" " + (i + 1) + " Subject " + cert.getSubjectDN()); log(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); log(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); log(" md5 " + toHexString(md5.digest())); } if (certificateIndex >= 0) { int k; k = certificateIndex; X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); try { ks.store(out, passphraseArray); } finally { out.close(); } log("Added certificate " + cert + " to keystore 'jssecacerts' using alias '" + alias + "'"); } } catch (KeyStoreException e) { throw new BuildException(e); } catch (IOException e) { throw new BuildException(e); } catch (NoSuchAlgorithmException e) { throw new BuildException(e); } catch (CertificateException e) { throw new BuildException(e); } catch (KeyManagementException e) { throw new BuildException(e); } }
public static void main(String[] args) throws Exception { String host; int port; char[] passphrase; if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { System.out.println("Usage: java InstallCert <host>[:port] [passphrase]"); return; } File file = new File("jssecacerts"); if (file.isFile() == false) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } System.out.println("Loading KeyStore " + file + "..."); KeyStore ks; InputStream in = new FileInputStream(file); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] {tm}, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]"); String line = reader.readLine().trim(); int k; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { System.out.println("KeyStore not changed"); return; } X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts"); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore 'jssecacerts' using alias '" + alias + "'"); }
public short InstallCert(String host, String pass, StringBuffer sb_mensaje) throws ServletException, IOException { try { int port; char[] passphrase; if (host != null) { String[] c = host.split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = pass == null ? "changeit" : pass; passphrase = p.toCharArray(); System.out.println(host + " " + p); } else { sb_mensaje.append("Modo de Uso: <host>[:port] [passphrase]"); return 3; } File file = new File("/usr/local/forseti/bin/jssecacerts"); if (file.isFile() == false) { char SEP = File.separatorChar; System.out.println(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); file = new File(dir, "jssecacerts"); if (file.isFile() == false) { file = new File(dir, "cacerts"); } } System.out.println("Cargando KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] {tm}, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Abriendo conexion a " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Empezando SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println("Sin errores, este certificado es ya de confianza"); } catch (SSLException e) { e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { sb_mensaje.append("No se puede obtener el chain del certificado del servidor"); return 3; } // BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); System.out.println("El Servidor envió: " + chain.length + " certificado(s):"); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); } // out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]"); String line = "1"; int k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream outs = new FileOutputStream("/usr/local/forseti/bin/jssecacerts"); ks.store(outs, passphrase); outs.close(); System.out.println(cert); sb_mensaje.append( JUtil.Msj("SAF", "ADMIN_SSL", "DLG", "MSJ-PROCOK", 5) + " '" + alias + "'"); // "Certificado añadido al keystore 'jssecacerts' usando alias '" + alias + // "'"); return 0; } catch (Exception e) { sb_mensaje.append("ERROR Exception InstallCert: " + e.getMessage()); return 3; } }
/** * Returns the IssuerDn of certificate on ICPBR_DN format thats works as a properties<br> * The toString Method of this class returns IssuerDn.getName()<br> * * @return ICPBR_DN * @see ICPBR_DN * @throws IOException */ public ICPBR_DN getCertificateIssuerDN() throws IOException { if (certificateFrom == null) { certificateFrom = new ICPBR_DN(certificate.getIssuerDN().getName()); } return certificateFrom; }
/** Read an existing PKCS#7 object from a DER encoded byte array */ public PKCS7SignedData(byte[] in, String provider) throws SecurityException, CRLException, InvalidKeyException, NoSuchProviderException, NoSuchAlgorithmException { ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(in)); // // Basic checks to make sure it's a PKCS#7 SignedData Object // DERObject pkcs; try { pkcs = din.readObject(); } catch (IOException e) { throw new SecurityException("can't decode PKCS7SignedData object"); } if (!(pkcs instanceof ASN1Sequence)) { throw new SecurityException("Not a valid PKCS#7 object - not a sequence"); } ContentInfo content = ContentInfo.getInstance(pkcs); if (!content.getContentType().equals(signedData)) { throw new SecurityException( "Not a valid PKCS#7 signed-data object - wrong header " + content.getContentType().getId()); } SignedData data = SignedData.getInstance(content.getContent()); certs = new ArrayList(); if (data.getCertificates() != null) { Enumeration ec = ASN1Set.getInstance(data.getCertificates()).getObjects(); while (ec.hasMoreElements()) { try { certs.add( new X509CertificateObject(X509CertificateStructure.getInstance(ec.nextElement()))); } catch (CertificateParsingException e) { throw new SecurityException(e.toString()); } } } crls = new ArrayList(); if (data.getCRLs() != null) { Enumeration ec = ASN1Set.getInstance(data.getCRLs()).getObjects(); while (ec.hasMoreElements()) { crls.add(new X509CRLObject(CertificateList.getInstance(ec.nextElement()))); } } version = data.getVersion().getValue().intValue(); // // Get the digest algorithm // digestalgos = new HashSet(); Enumeration e = data.getDigestAlgorithms().getObjects(); while (e.hasMoreElements()) { ASN1Sequence s = (ASN1Sequence) e.nextElement(); DERObjectIdentifier o = (DERObjectIdentifier) s.getObjectAt(0); digestalgos.add(o.getId()); } // // Get the SignerInfo // ASN1Set signerinfos = data.getSignerInfos(); if (signerinfos.size() != 1) { throw new SecurityException( "This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); } SignerInfo signerInfo = SignerInfo.getInstance(signerinfos.getObjectAt(0)); signerversion = signerInfo.getVersion().getValue().intValue(); IssuerAndSerialNumber isAnds = signerInfo.getIssuerAndSerialNumber(); // // Get the signing certificate // BigInteger serialNumber = isAnds.getCertificateSerialNumber().getValue(); X509Principal issuer = new X509Principal(isAnds.getName()); for (Iterator i = certs.iterator(); i.hasNext(); ) { X509Certificate cert = (X509Certificate) i.next(); if (serialNumber.equals(cert.getSerialNumber()) && issuer.equals(cert.getIssuerDN())) { signCert = cert; break; } } if (signCert == null) { throw new SecurityException( "Can't find signing certificate with serial " + serialNumber.toString(16)); } digestAlgorithm = signerInfo.getDigestAlgorithm().getObjectId().getId(); digest = signerInfo.getEncryptedDigest().getOctets(); digestEncryptionAlgorithm = signerInfo.getDigestEncryptionAlgorithm().getObjectId().getId(); sig = Signature.getInstance(getDigestAlgorithm(), provider); sig.initVerify(signCert.getPublicKey()); }
public String getIssuer() { return cert.getIssuerDN().getName(); }
/** * Installs a certificate from the server into a local certificate store. * * @param host the HTTPS base server host to get the certificate from * @param port the port of the server * @param passphrase the passphrase to access/set the cert store if it does not exist, defaults to * "changeit" if null is provided * @throws Exception if something goes wrong */ public static void installCert(String host, int port, char[] passphrase) throws Exception { if (passphrase == null) { passphrase = "changeit".toCharArray(); } File file; if (certStore != null) { file = certStore; } else { file = new File("jssecacerts"); } if (!file.isFile()) { char SEP = File.separatorChar; File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); file = new File(dir, "jssecacerts"); if (!file.isFile()) { file = new File(dir, "cacerts"); } } certStore = file; LOG.debug("Loading KeyStore {}", file); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] {tm}, null); SSLSocketFactory factory = context.getSocketFactory(); // Try to reconnect in case there are newly launched instances and they're not fully up yet SSLSocket socket = null; int trial = 0; boolean success = false; ConnectException connectException = null; do { try { LOG.info("Opening connection to {}:{}", host, port); socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); success = true; } catch (ConnectException e) { connectException = e; Thread.sleep(1500); } } while (!success && trial++ < 10); if (!success) { throw connectException; } try { LOG.debug("Starting SSL handshake..."); socket.startHandshake(); socket.close(); LOG.debug("No errors, certificate is already trusted"); } catch (SSLException e) { LOG.debug("Cert is NOT trusted: {}", e.getMessage()); } X509Certificate[] chain = tm.chain; if (chain == null) { LOG.warn("Could not obtain server certificate chain"); return; } LOG.debug("Server sent " + chain.length + " certificate(s):"); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; LOG.debug(" " + (i + 1) + " Subject " + cert.getSubjectDN()); LOG.debug(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); LOG.debug(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); LOG.debug(" md5 " + toHexString(md5.digest())); } int k = 0; X509Certificate cert = chain[k]; // now just using the hostname instead of : String alias = host + "-" + ( k + 1 ); ks.setCertificateEntry(host, cert); OutputStream out = new FileOutputStream("jssecacerts"); ks.store(out, passphrase); out.close(); LOG.debug("cert = {}", cert); LOG.debug("Added certificate to keystore 'jssecacerts' using alias '" + host + "'"); }
} else { ContentInfo var19 = ContentInfo.getInstance(var16); DERObjectIdentifier var20 = var19.getContentType(); DERObjectIdentifier var21 = signedData; if(!var20.equals(var21)) { StringBuilder var22 = (new StringBuilder()).append("Not a valid PKCS#7 signed-data object - wrong header "); String var23 = var19.getContentType().getId(); String var24 = var22.append(var23).toString(); throw new SecurityException(var24); } else { SignedData var25 = SignedData.getInstance(var19.getContent()); ArrayList var26 = new ArrayList(); this.certs = var26; Enumeration var27; if(var25.getCertificates() != null) { var27 = ASN1Set.getInstance(var25.getCertificates()).getObjects(); while(var27.hasMoreElements()) { try { Collection var28 = this.certs; X509CertificateStructure var29 = X509CertificateStructure.getInstance(var27.nextElement()); X509CertificateObject var30 = new X509CertificateObject(var29); var28.add(var30); } catch (CertificateParsingException var80) { String var32 = var80.toString(); throw new SecurityException(var32); } } } ArrayList var33 = new ArrayList(); this.crls = var33; if(var25.getCRLs() != null) { var27 = ASN1Set.getInstance(var25.getCRLs()).getObjects(); while(var27.hasMoreElements()) { Collection var34 = this.crls; CertificateList var35 = CertificateList.getInstance(var27.nextElement()); X509CRLObject var36 = new X509CRLObject(var35); var34.add(var36); } } int var38 = var25.getVersion().getValue().intValue(); this.version = var38; HashSet var39 = new HashSet(); this.digestalgos = var39; Enumeration var40 = var25.getDigestAlgorithms().getObjects(); while(var40.hasMoreElements()) { ASN1Sequence var41 = (ASN1Sequence)var40.nextElement(); byte var42 = 0; DERObjectIdentifier var43 = (DERObjectIdentifier)var41.getObjectAt(var42); Set var44 = this.digestalgos; String var45 = var43.getId(); var44.add(var45); } ASN1Set var47 = var25.getSignerInfos(); int var48 = var47.size(); byte var49 = 1; if(var48 != var49) { throw new SecurityException("This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); } else { SignerInfo var50 = SignerInfo.getInstance(var47.getObjectAt(0)); int var51 = var50.getVersion().getValue().intValue(); this.signerversion = var51; IssuerAndSerialNumber var52 = var50.getIssuerAndSerialNumber(); BigInteger var53 = var52.getCertificateSerialNumber().getValue(); X509Principal var54 = new X509Principal; X509Name var55 = var52.getName(); var54.<init>(var55); Iterator var58 = this.certs.iterator(); while(var58.hasNext()) { X509Certificate var59 = (X509Certificate)var58.next(); BigInteger var60 = var59.getSerialNumber(); if(var53.equals(var60)) { Principal var63 = var59.getIssuerDN(); if(var54.equals(var63)) { this.signCert = var59; break; } } } if(this.signCert == null) { StringBuilder var67 = (new StringBuilder()).append("Can\'t find signing certificate with serial "); byte var69 = 16; String var70 = var53.toString(var69); String var71 = var67.append(var70).toString(); throw new SecurityException(var71); } else { String var72 = var50.getDigestAlgorithm().getObjectId().getId(); this.digestAlgorithm = var72; byte[] var73 = var50.getEncryptedDigest().getOctets(); this.digest = var73; String var74 = var50.getDigestEncryptionAlgorithm().getObjectId().getId(); this.digestEncryptionAlgorithm = var74; String var75 = this.getDigestAlgorithm(); Signature var77 = Signature.getInstance(var75, var2); this.sig = var77; Signature var78 = this.sig; PublicKey var79 = this.signCert.getPublicKey(); var78.initVerify(var79); } }
protected static boolean isSelfIssued(X509Certificate cert) { return cert.getSubjectDN().equals(cert.getIssuerDN()); }