List of usage examples for java.security.cert X509Certificate getIssuerDN
public abstract Principal getIssuerDN();
From source file:org.cesecore.certificates.ocsp.CanLogCache.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 . c o 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 */ private boolean checkCertInList(X509Certificate cert, Map<String, X509Certificate> trustedCerts) { String key = cert.getIssuerDN() + ";" + cert.getSerialNumber().toString(16); return trustedCerts.get(key) != null; }
From source file:org.syncany.plugins.webdav.WebdavTransferManager.java
private String formatCertificate(X509Certificate cert) { try {//from w w w . j av a 2s. c o m CipherUtil.enableUnlimitedStrength(); // Dirty! String checksumMd5 = formatChecksum(createChecksum(cert.getEncoded(), "MD5")); String checksumSha1 = formatChecksum(createChecksum(cert.getEncoded(), "SHA1")); String checksumSha256 = formatChecksum(createChecksum(cert.getEncoded(), "SHA256")); StringBuilder sb = new StringBuilder(); sb.append(String.format("Owner: %s\n", cert.getSubjectDN().getName())); sb.append(String.format("Issuer: %s\n", cert.getIssuerDN().getName())); sb.append(String.format("Serial number: %d\n", cert.getSerialNumber())); sb.append(String.format("Valid from %s until: %s\n", cert.getNotBefore().toString(), cert.getNotAfter().toString())); sb.append("Certificate fingerprints:\n"); sb.append(String.format(" MD5: %s\n", checksumMd5)); sb.append(String.format(" SHA1: %s\n", checksumSha1)); sb.append(String.format(" SHA256: %s", checksumSha256)); return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.viafirma.nucleo.validacion.CRLUtil.java
/** * Recupero los puntos de distribucin//w ww.j a va 2s.c o m * * @param certificadoX509 * @return */ private List<String> getCrlPuntosDeDistribucion(X509Certificate certificadoX509) throws CertificateParsingException { try { log.debug("Recuperando puntos de distribucin CRL del certificado: " + certificadoX509.getSubjectDN()); // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds // segun el RFC 3280 seccin 4.2.1.14) byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS); if (val1 == null) { if (certificadoX509.getSubjectDN().getName().equals(certificadoX509.getIssuerDN().getName())) { log.debug("El certificado es un certificado raiz: " + certificadoX509.getSubjectDN().getName()); } else { log.warn(" El certificado NO tiene punto de distribucin de CRL : " + certificadoX509.getSubjectDN().getName()); } return Collections.emptyList(); } else { ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1)); DERObject derObj = oAsnInStream.readObject(); DEROctetString dos = (DEROctetString) derObj; byte[] val2 = dos.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2)); DERObject derObj2 = oAsnInStream2.readObject(); // Map<String,String> propiedades= new HashMap<String,String>(); List<String> urls = getDERValue(derObj2); return urls; /* * CertificadoHelper.getCurrentInstance().readPropiedadesOid(OID_CRLS,derObj2,propiedades); * if(log.isDebugEnabled())log.debug("Informacin sobre CRls del * certificado que ha sido recuperada: "+propiedades); // por * simplificar, aunque el certificado informe de varias crls que * utilizar. Solo trabajamos con la primera List listaCrls=new * ArrayList(1); listaCrls.add(propiedades.get(OID_CRLS)); * return listaCrls;//listaCrls.addAll(getDERValue(derObj2)) */} } catch (Exception e) { e.printStackTrace(); throw new CertificateParsingException(e.toString()); } }
From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java
/** * Test conversion to byte array and back. *///from ww w .j av a 2 s. c o m @Test public void testTestRoundtrip() throws GeneralSecurityException { populate(builder); X509Certificate expected = builder.build(keyPair.getPrivate()); X509Certificate actual = certUtil.getCertificate(expected.getEncoded()); assertEquals(actual.getSerialNumber(), expected.getSerialNumber()); assertEquals(actual.getIssuerDN().toString(), expected.getIssuerDN().toString()); assertEquals(actual.getSubjectDN().toString(), expected.getSubjectDN().toString()); assertEquals(actual.getNotBefore(), expected.getNotBefore()); assertEquals(actual.getNotAfter(), expected.getNotAfter()); }
From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java
/** * @see com.otterca.persistence.dao.X509CertificateDao#put(java.security.cert * .X509Certificate)/*ww w. j a v a2s.co m*/ */ public void put(X509Certificate cert) throws IOException, CertificateEncodingException { // TODO: we want cert's issuer to be its parent. For now certs don't // have parents. Key key = generateKey(cert); Entity e = new Entity(key); // also set parent... e.setProperty(CERTIFICATE, new Blob(cert.getEncoded())); // up to 20 octets - 40 characters e.setProperty(SERIAL_NUMBER, cert.getSerialNumber().toString(16)); // up to 500 unicode characters e.setProperty(SUBJECT_DN, cert.getSubjectDN().getName()); // up to 500 unicode characters e.setProperty(ISSUER_DN, cert.getIssuerDN().getName()); e.setProperty(NOT_BEFORE, cert.getNotBefore()); e.setProperty(NOT_AFTER, cert.getNotAfter()); // RFC search criteria e.setProperty(COMMON_NAME, x509CertUtil.getName(cert)); e.setProperty(FINGERPRINT, x509CertUtil.getFingerprint(cert)); e.setProperty(CERT_HASH, x509CertUtil.getCertificateHash(cert)); e.setProperty(ISSUER_HASH, x509CertUtil.getIHash(cert)); e.setProperty(SUBJECT_HASH, x509CertUtil.getSHash(cert)); // e.setProperty(AKID_HASH, x509CertUtil.getAkidHash(cert)); e.setProperty(SKID_HASH, x509CertUtil.getSkidHash(cert)); // e.setProperty(IANDS_HASH, x509CertUtil.getIandSHash(cert)); // e.setProperty(EMAIL) ?... e.setUnindexedProperty(TRUSTED, false); e.setUnindexedProperty(STATUS, UNKNOWN); datastore.put(e); }
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 w w . 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.vmware.bdd.cli.http.DefaultTrustManager.java
@Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { String errorMsg = ""; InputStream in = null;//from w w w. jav a 2 s . c o m OutputStream out = null; // load key store file try { char[] pwd = cliProperties.readKeyStorePwd(); File file = new File(KEY_STORE_FILE); if (file.exists() && file.isFile()) { keyStore.load(new FileInputStream(file), pwd); } else { //init an empty keystore keyStore.load(null, pwd); } // show certificate informations MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); String md5Fingerprint = ""; String sha1Fingerprint = ""; SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy/MM/dd"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); md5Fingerprint = ByteArrayUtils.byteArrayToHexString(md5.digest()); sha1Fingerprint = ByteArrayUtils.byteArrayToHexString(sha1.digest()); if (keyStore.getCertificate(md5Fingerprint) != null) { if (i == chain.length - 1) { return; } else { continue; } } System.out.println(); System.out.println("Server Certificate"); System.out.println("================================================================"); System.out.println("Subject: " + cert.getSubjectDN()); System.out.println("Issuer: " + cert.getIssuerDN()); System.out.println("SHA Fingerprint: " + sha1Fingerprint); System.out.println("MD5 Fingerprint: " + md5Fingerprint); System.out.println("Issued on: " + dateFormate.format(cert.getNotBefore())); System.out.println("Expires on: " + dateFormate.format(cert.getNotAfter())); System.out.println("Signature: " + cert.getSignature()); System.out.println(); if (checkExpired(cert.getNotBefore(), cert.getNotAfter())) { throw new CertificateException("The security certificate has expired."); } ConsoleReader reader = new ConsoleReader(); // Set prompt message reader.setPrompt(Constants.PARAM_PROMPT_ADD_CERTIFICATE_MESSAGE); // Read user input String readMsg; if (RunWayConfig.getRunType().equals(RunWayConfig.RunType.MANUAL)) { readMsg = reader.readLine().trim(); } else { readMsg = "yes"; } if ("yes".equalsIgnoreCase(readMsg) || "y".equalsIgnoreCase(readMsg)) { { // add new certificate into key store file. keyStore.setCertificateEntry(md5Fingerprint, cert); out = new FileOutputStream(KEY_STORE_FILE); keyStore.store(out, pwd); CommonUtil.setOwnerOnlyReadWrite(KEY_STORE_FILE); // save keystore password cliProperties.saveKeyStorePwd(pwd); } } else { if (i == chain.length - 1) { throw new CertificateException("Could not find a valid certificate in the keystore."); } else { continue; } } } } catch (FileNotFoundException e) { errorMsg = "Cannot find the keystore file: " + e.getMessage(); } catch (NoSuchAlgorithmException e) { errorMsg = "SSL Algorithm not supported: " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); errorMsg = "IO error: " + e.getMessage(); } catch (KeyStoreException e) { errorMsg = "Keystore error: " + e.getMessage(); } catch (ConfigurationException e) { errorMsg = "cli.properties access error: " + e.getMessage(); } finally { if (!CommandsUtils.isBlank(errorMsg)) { System.out.println(errorMsg); logger.error(errorMsg); } if (in != null) { try { in.close(); } catch (IOException e) { logger.warn("Input stream of serengeti.keystore close failed."); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Output stream of serengeti.keystore close failed."); } } } }
From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java
private CertData fillCertData(X509Certificate cert, String alise, Format formatter) throws CertificateEncodingException { CertData certData = null;//from www . j ava 2 s.c o m if (includeCert) { certData = new CertDataDetail(); } else { certData = new CertData(); } certData.setAlias(alise); certData.setSubjectDN(cert.getSubjectDN().getName()); certData.setIssuerDN(cert.getIssuerDN().getName()); certData.setSerialNumber(cert.getSerialNumber()); certData.setVersion(cert.getVersion()); certData.setNotAfter(formatter.format(cert.getNotAfter())); certData.setNotBefore(formatter.format(cert.getNotBefore())); certData.setPublicKey(Base64.encode(cert.getPublicKey().getEncoded())); if (includeCert) { ((CertDataDetail) certData).setCertificate(cert); } return certData; }
From source file:org.viafirma.nucleo.validacion.CRLUtil.java
/** * Se conecta a la url indicada y se descarga las crls. No se esta usando * *******************!!! En desarrollo, no funciona * /*from ww w .j a v a 2 s . c o m*/ * @param hostURL * @return * @throws CRLException * No se ha podido recuperar el listado * @throws CertificateParsingException */ @SuppressWarnings("unchecked") private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509) throws CRLException, CertificateParsingException { // ************************ // recupero las propiedades para realizar la busqueda en LDAP. // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1} Map<String, String> propiedades = new HashMap<String, String>(); try { log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: " + certificadoX509.getIssuerDN()); // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds // segun el RFC 3280 seccin 4.2.1.14) byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS); if (val1 == null) { log.debug(" El certificado NO tiene punto de distribucin de CRL "); } else { ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1)); DERObject derObj = oAsnInStream.readObject(); DEROctetString dos = (DEROctetString) derObj; byte[] val2 = dos.getOctets(); ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2)); DERObject derObj2 = oAsnInStream2.readObject(); X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades); } } catch (Exception e) { e.printStackTrace(); throw new CertificateParsingException(e.toString()); } // comprobamos la configuracin if (isSomeFNMTValorNull()) { throw new CRLException( "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :" + Constantes.CONEXION_LDAP_CRL_FNMT); } String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN(); log.debug("Buscando en el LDAP " + CN); // ********************************************** // Nos conectamos al LDAP para recuperar la CRLs. Properties env = new Properties(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, fnmtLDAPHostURL); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal); env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial); env.put(Context.REFERRAL, "follow"); try { DirContext ctx = new InitialDirContext(env); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls)); log.debug("Se ha logrado conectar al LDAP"); if (namings.hasMore()) { log.debug("Recuperando el contenido de la CRLs"); // recupero el resultado SearchResult resultado = ((SearchResult) namings.next()); // recupero todos los atributos del resultado Attributes avals = resultado.getAttributes(); // recupero los bytes. byte[] bytes; if ((avals.get("certificateRevocationList;binary")) != null) { log.debug("Atributos deben estar en binario"); Attribute atributo = (avals.get("certificateRevocationList;binary")); bytes = ((byte[]) atributo.get()); } else { log.debug("Atributos en exadecimal En Hexadecimal"); Attribute atributo = (avals.get("certificateRevocationList")); bytes = ((byte[]) atributo.get()); log.debug("Por implementar"); } if (bytes != null) { ByteArrayInputStream io = new ByteArrayInputStream(bytes); return io; } } } catch (NamingException e) { log.error("No se puede conectar al LDAP!!", e); } return null; }
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
private void checkStrongCrypto(X509Certificate cert) throws CertificateException { String algo = cert.getSigAlgName().toLowerCase(); if (algo.contains("md5")) { debug("cert uses weak crypto: " + algo); if (mNotifyVerificationFail) showCertMessage(mContext.getString(R.string.warning_weak_crypto), cert.getIssuerDN().getName(), cert, null);/* w w w. j ava 2s . c o m*/ throw new CertificateException("issuer uses weak crypto: " + algo); } }