List of usage examples for java.security.cert X509Certificate getIssuerDN
public abstract Principal getIssuerDN();
From source file:org.wso2.carbon.identity.relyingparty.saml.IssuerCertificateUtil.java
/** * Do a white list check//from w w w .ja v a 2s. com * * @param whiteList Array of Lists. One Array element contains the Issuer's cert DN * @param cert * @return * @throws RelyingPartyException */ public static boolean isWhiteListed(List[] whiteList, X509Certificate cert) throws RelyingPartyException { if (cert == null) { throw new RelyingPartyException("noCertInToken"); } if (whiteList != null && whiteList.length > 0) { List certDN = getDNOfIssuer(cert.getIssuerDN().getName()); for (int i = 0; i < whiteList.length; i++) { List issuerDN = whiteList[i]; if (certDN.equals(issuerDN)) { return true; } } } return false; }
From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java
/** * For debuging only. Prints out keystore certificate chain. * * @param keystore Keystore to print out. * @throws KeyStoreException If the keystore is broken. *///from w ww .j a v a 2 s . co m public static void printTrustCerts(KeyStore keystore) throws KeyStoreException { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); String message = "Trusted certificate '" + alias + "':"; Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; message += "\n Subject DN: " + cert.getSubjectDN(); message += "\n Signature Algorithm: " + cert.getSigAlgName(); message += "\n Valid from: " + cert.getNotBefore(); message += "\n Valid until: " + cert.getNotAfter(); message += "\n Issuer: " + cert.getIssuerDN(); } log.info(message); } }
From source file:fi.laverca.Pkcs7.java
/** * Read the certificates used to sign a PKCS7 SignedData. * // w w w. j a v a 2s .com * @param sd PKCS7 SignedData * @return List of X509 certificates * @throws FiComException if no certificate or signer info is found from the data */ public static List<X509Certificate> getSignerCerts(final SignedData sd) throws FiComException { // 0. Setup. // 1. Read PKCS7.Certificates to get all possible certs. // 2. Read PKCS7.SignerInfo to get all signers. // 3. Look up matching certificates. // 4. Return the list. // 0. Setup. if (sd == null) { throw new IllegalArgumentException("null input"); } List<X509Certificate> signerCerts = new ArrayList<X509Certificate>(); // 1. Read PKCS7.Certificates to get all possible certs. log.debug("Read all certs"); List<X509Certificate> certs = readCerts(sd); if (certs.isEmpty()) { throw new FiComException("PKCS7 SignedData certificates not found"); } // 2. Read PKCS7.SignerInfo to get all signers. log.debug("Read SignerInfo"); List<SignerInfo> signerInfos = readSignerInfos(sd); if (signerInfos.isEmpty()) { throw new FiComException("PKCS7 SignedData signerInfo not found"); } // 3. Verify that signerInfo cert details match the cert on hand log.debug("Matching cert and SignerInfo details"); for (SignerInfo si : signerInfos) { for (X509Certificate c : certs) { String siIssuer = readIssuer(si); String siSerial = readSerial(si); String cIssuer = c.getIssuerDN().toString(); String cSerial = c.getSerialNumber().toString(); if (dnsEqual(siIssuer, cIssuer) && siSerial.equals(cSerial)) { signerCerts.add(c); log.debug("Cert does match signerInfo"); log.debug("SignerInfo issuer:serial = " + siIssuer + ":" + siSerial); log.debug("Certificates issuer:serial = " + cIssuer + ":" + cSerial); } else { log.debug("Cert does not match signerInfo"); log.debug("SignerInfo issuer:serial = " + siIssuer + ":" + siSerial); log.debug("Certificates issuer:serial = " + cIssuer + ":" + cSerial); } } } // 4. Return the list. log.debug("Returning " + signerCerts.size() + " certs"); return signerCerts; }
From source file:org.wso2.carbon.identity.relyingparty.saml.IssuerCertificateUtil.java
/** * This method checks whether the certificate is present in the certificate store *///from www . j ava2 s. c o m public static boolean checkSystemStore(X509Certificate signedCert, KeyStore systemStore) throws Exception { if (signedCert == null || systemStore == null) { throw new RelyingPartyException("invalidInputParams"); } // validity period signedCert.checkValidity(); try { return systemStore.containsAlias(signedCert.getIssuerDN().getName()); } catch (KeyStoreException e) { log.error("The keystore has not been initialized", e); throw new RelyingPartyException("errorLoadingTrustedKeystore", e); } }
From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java
public static Hashtable getCertificatesFromDirectory(String certificateDir) throws IOException { // read all files from trustDir, expect that they are PEM formatted certificates CertTools.installBCProvider();// w w w . j av a 2 s. c o m File dir = new File(certificateDir); Hashtable trustedCerts = new Hashtable(); if (dir == null || dir.isDirectory() == false) { m_log.error(dir.getCanonicalPath() + " is not a directory."); throw new IllegalArgumentException(dir.getCanonicalPath() + " is not a directory."); } File files[] = dir.listFiles(); if (files == null || files.length == 0) { String errMsg = intres.getLocalizedMessage("ocsp.errornotrustfiles", dir.getCanonicalPath()); m_log.error(errMsg); } for (int i = 0; i < files.length; i++) { final String fileName = files[i].getCanonicalPath(); // Read the file, don't stop completely if one file has errors in it try { byte[] bytes = FileTools.getBytesFromPEM(FileTools.readFiletoBuffer(fileName), CertTools.BEGIN_CERTIFICATE, CertTools.END_CERTIFICATE); X509Certificate cert = (X509Certificate) CertTools.getCertfromByteArray(bytes); String key = cert.getIssuerDN() + ";" + cert.getSerialNumber().toString(16); trustedCerts.put(key, cert); } catch (CertificateException e) { String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir", e.getMessage()); m_log.error(errMsg, e); } catch (IOException e) { String errMsg = intres.getLocalizedMessage("ocsp.errorreadingfile", fileName, "trustDir", e.getMessage()); m_log.error(errMsg, e); } } return trustedCerts; }
From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java
/** * Get Certificate thumb print and Issuer Name from the ACS token. * @param acsToken the acs token// w w w . j ava 2 s. co m * @return returnData the Map containing Thumb print and issuer name of X509Certiificate * @throws NoSuchAlgorithmException * @throws CertificateEncodingException */ public static Map<String, String> getCertificateThumbPrintAndIssuerName(String acsToken) throws NoSuchAlgorithmException, CertificateEncodingException { byte[] acsTokenByteArray = null; Map<String, String> returnData = new HashMap<String, String>(); try { acsTokenByteArray = acsToken.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { return null; } DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder docBuilder; String issuerName = null; StringBuffer thumbprint = null; try { docBuilder = builderFactory.newDocumentBuilder(); Document resultDoc = docBuilder.parse(new ByteArrayInputStream(acsTokenByteArray)); Element keyInfo = (Element) resultDoc.getDocumentElement() .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "KeyInfo").item(0); NodeList x509CertNodeList = keyInfo.getElementsByTagName("X509Certificate"); Element x509CertNode = (Element) x509CertNodeList.item(0); if (x509CertNode == null) { return null; } //generating Certificate to retrieve its detail. String x509CertificateData = x509CertNode.getTextContent(); InputStream inStream = new Base64InputStream(new ByteArrayInputStream(x509CertificateData.getBytes())); CertificateFactory x509CertificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate x509Certificate = (X509Certificate) x509CertificateFactory .generateCertificate(inStream); String issuerDN = x509Certificate.getIssuerDN().toString(); String[] issuerDNData = issuerDN.split("="); issuerName = issuerDNData[1]; MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] der = x509Certificate.getEncoded(); md.update(der); thumbprint = new StringBuffer(); thumbprint.append(Hex.encodeHex(md.digest())); } catch (Exception e) { e.printStackTrace(); } returnData.put("IssuerName", issuerName); returnData.put("Thumbprint", thumbprint.toString().toUpperCase()); return returnData; }
From source file:org.ejbca.core.protocol.ocsp.OCSPUtil.java
/** * Checks to see if a certificate is in a list of certificate. * Comparison is made on SerialNumber/*from w w w . j a va 2 s . co m*/ * @param cert the certificate to look for * @param trustedCerts the list (Hashtable) to look in * @return true if cert is in trustedCerts, false otherwise */ public static boolean checkCertInList(X509Certificate cert, Hashtable trustedCerts) { //String key = CertTools.getIssuerDN(cert)+";"+cert.getSerialNumber().toString(16); String key = cert.getIssuerDN() + ";" + cert.getSerialNumber().toString(16); Object found = trustedCerts.get(key); if (found != null) { return true; } return false; }
From source file:org.openhealthtools.openatna.net.ConnectionCertificateHandler.java
/** * For debuging only. Prints out keystore certificate chain. * * @param keystore Keystore to print out. * @throws KeyStoreException If the keystore is broken. *//*from w w w. j ava2 s .c o m*/ public static void printKeyCertificates(KeyStore keystore) throws KeyStoreException { Enumeration<String> aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { String message = "Certificate chain '" + alias + "':"; int i = 1; for (Certificate cert : certs) { if (cert instanceof X509Certificate) { X509Certificate Xcert = (X509Certificate) cert; message += "\n Certificate " + i++ + ":"; message += "\n Subject DN: " + Xcert.getSubjectDN(); message += "\n Signature Algorithm: " + Xcert.getSigAlgName(); message += "\n Valid from: " + Xcert.getNotBefore(); message += "\n Valid until: " + Xcert.getNotAfter(); message += "\n Issuer: " + Xcert.getIssuerDN(); } } log.info(message); } } }
From source file:com.dbay.apns4j.tools.ApnsTools.java
public final static SocketFactory createSocketFactory(InputStream keyStore, String password, String keystoreType, String algorithm, String protocol) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException, CertificateExpiredException { char[] pwdChars = password.toCharArray(); KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(keyStore, pwdChars);/*w ww . j a v a 2 s . c o m*/ // ?? Enumeration<String> enums = ks.aliases(); String alias = ""; if (enums.hasMoreElements()) { alias = enums.nextElement(); } if (StringUtils.isNotEmpty(alias)) { X509Certificate certificate = (X509Certificate) ks.getCertificate(alias); if (null != certificate) { String type = certificate.getType(); int ver = certificate.getVersion(); String name = certificate.getSubjectDN().getName(); String serialNumber = certificate.getSerialNumber().toString(16); String issuerDN = certificate.getIssuerDN().getName(); String sigAlgName = certificate.getSigAlgName(); String publicAlgorithm = certificate.getPublicKey().getAlgorithm(); Date before = certificate.getNotBefore(); Date after = certificate.getNotAfter(); String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss"); String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss"); // ?? long expire = DateUtil.getNumberOfDaysBetween(new Date(), after); if (expire <= 0) { if (LOG.isErrorEnabled()) { LOG.error( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, Math.abs(expire)); } throw new CertificateExpiredException("??[" + Math.abs(expire) + "]"); } if (LOG.isInfoEnabled()) { LOG.info( "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?", name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr, afterStr, expire); } } } KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm); kf.init(ks, pwdChars); TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init((KeyStore) null); SSLContext context = SSLContext.getInstance(protocol); context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java
private static final void importCertificate(final String url, final KeyStore trustStore) throws Exception { final URL url2 = new URL(url); final SSLContext sslContext = SSLContext.getInstance("TLS"); final TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); final X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0]; final SavingTrustManager trustManager = new SavingTrustManager(defaultTrustManager); sslContext.init(null, new TrustManager[] { trustManager }, null); final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(url2.getHost(), url2.getPort() > 0 ? url2.getPort() : 443); socket.setSoTimeout(10000);/* www . j a v a 2 s . com*/ try { socket.startHandshake(); socket.close(); } catch (SSLException e) { } final X509Certificate[] chain = trustManager.chain; if (chain == null) { LOGGER.error("Could not obtain server certificate chain from: " + url); return; } final MessageDigest sha1 = MessageDigest.getInstance("SHA1"); final MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { final X509Certificate cert = chain[i]; final String alias = url2.getHost() + "-" + (i + 1); if (!trustStore.containsAlias(alias)) { sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); LOGGER.trace("Importing certificate to trusted keystore >> " + "Subject: " + cert.getSubjectDN() + ", Issuer: " + cert.getIssuerDN() + ", SHA1: " + printHexBinary(sha1.digest()) + ", MD5: " + printHexBinary(md5.digest()) + ", Alias: " + alias); trustStore.setCertificateEntry(alias, cert); } } }