List of usage examples for java.security.cert X509Certificate checkValidity
public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException;
From source file:org.apache.xml.security.keys.storage.implementations.CertsInFilesystemDirectoryResolver.java
/** * Method readCertsFromHarddrive//from w ww . jav a2 s .c o m * * @throws StorageResolverException */ private void readCertsFromHarddrive() throws StorageResolverException { File certDir = new File(this.merlinsCertificatesDir); List<String> al = new ArrayList<String>(); String[] names = certDir.list(); for (int i = 0; i < names.length; i++) { String currentFileName = names[i]; if (currentFileName.endsWith(".crt")) { al.add(names[i]); } } CertificateFactory cf = null; try { cf = CertificateFactory.getInstance("X.509"); } catch (CertificateException ex) { throw new StorageResolverException("empty", ex); } if (cf == null) { throw new StorageResolverException("empty"); } for (int i = 0; i < al.size(); i++) { String filename = certDir.getAbsolutePath() + File.separator + (String) al.get(i); File file = new File(filename); boolean added = false; String dn = null; try { FileInputStream fis = new FileInputStream(file); X509Certificate cert = (X509Certificate) cf.generateCertificate(fis); fis.close(); //add to ArrayList cert.checkValidity(); this.certs.add(cert); dn = cert.getSubjectDN().getName(); added = true; } catch (FileNotFoundException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } catch (IOException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } catch (CertificateNotYetValidException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } catch (CertificateExpiredException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } catch (CertificateException ex) { if (log.isDebugEnabled()) { log.debug("Could not add certificate from file " + filename, ex); } } if (added && log.isDebugEnabled()) { log.debug("Added certificate: " + dn); } } }
From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java
private X509Certificate getCertificate(String certificate) { if (certificate.isEmpty()) { return null; }//from w w w .j ava 2 s . c om if (certificate.contains(KeyStoreConstant.BEGIN_CERTIFICATE)) { final int fIdx = certificate.indexOf(KeyStoreConstant.BEGIN_CERTIFICATE) + KeyStoreConstant.BEGIN_CERTIFICATE.length(); final int sIdx = certificate.indexOf(KeyStoreConstant.END_CERTIFICATE); certificate = certificate.substring(fIdx, sIdx); } final byte[] byteCert = Base64.decodeBase64(certificate); final InputStream inputStreamCert = new ByteArrayInputStream(byteCert); CertificateFactory certFactory; try { certFactory = CertificateFactory.getInstance("X.509"); final X509Certificate newCert = (X509Certificate) certFactory.generateCertificate(inputStreamCert); newCert.checkValidity(); return newCert; } catch (final CertificateException e) { LOG.error("Failed to get certificate", e); return null; } }
From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java
public String getValidity() { String validity = "The cert is valid"; try {//from www . ja va2 s.com X509Certificate cert = getCertificateList().get(0); cert.checkValidity(); } catch (CertificateExpiredException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); validity = e.toString(); } catch (CertificateNotYetValidException e) { LOG.log(Level.WARNING, "Unexpected Exception", e); validity = e.toString(); } return validity; }
From source file:org.sipfoundry.sipxconfig.cert.CertificateManagerImpl.java
void validateCert(String certTxt, String keyTxt) { X509Certificate cert = CertificateUtils.readCertificate(certTxt); try {/* w ww.j ava 2s .c o m*/ cert.checkValidity(); } catch (CertificateExpiredException e) { throw new UserException("Certificate has expired."); } catch (CertificateNotYetValidException e) { throw new UserException("Certificate valid date range is in the future, it is not yet valid."); } if (StringUtils.isNotBlank(keyTxt)) { CertificateUtils.readCertificateKey(keyTxt); } // to do, validate key w/cert and cert w/authorities }
From source file:org.kaazing.maven.plugins.TrustStoreMojo.java
KeyStore getTrustStore(Map<String, String> certs, String storeType) throws Exception { KeyStore ks = KeyStore.getInstance(storeType); // Initialize an empty keystore ks.load(null, null);//from w ww . j av a 2s. com CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); for (Map.Entry<String, String> elt : certs.entrySet()) { String alias = elt.getKey(); try { ByteArrayInputStream bais = new ByteArrayInputStream(elt.getValue().getBytes(UTF8)); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(bais); cert.checkValidity(); getLog().info(String.format("Adding certificate with alias '%s'", alias)); ks.setCertificateEntry(alias, cert); } catch (CertificateExpiredException cee) { getLog().error(String.format("NOT Adding certificate %s: %s", alias, cee)); } catch (CertificateNotYetValidException cnyve) { getLog().error(String.format("NOT Adding certificate %s: %s", alias, cnyve)); } } return ks; }
From source file:com.jonbanjo.cupsprint.CertificateActivity.java
public void doimport(View view) { try {/*from ww w. ja v a 2 s . c om*/ String url = "https://" + host.getText().toString() + ":" + port.getText().toString(); importButton.setEnabled(false); new importer().execute(url).get(3000, TimeUnit.MILLISECONDS); } catch (Exception e) { } finally { importButton.setEnabled(true); } if (certChain == null) { return; } for (X509Certificate cert : certChain) { try { cert.checkValidity(); } catch (Exception e) { showToast(e.toString()); return; } } String certString = certChain[0].toString(); final String alias = certChain[0].getSubjectX500Principal().getName(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Add Certificate?").setMessage(certString) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); trustStore.setKeyEntry(alias, privateKey, JfSSLScheme.password.toCharArray(), certChain); FileOutputStream outputStream = openFileOutput(JfSSLScheme.trustfile, MODE_PRIVATE); trustStore.store(outputStream, JfSSLScheme.password.toCharArray()); outputStream.flush(); outputStream.close(); certListAdaptor.add(alias); } catch (Exception e) { System.out.println(e.toString()); return; } } }).setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog dialog = builder.create(); dialog.show(); }
From source file:net.sf.dsig.verify.XmldsigVerifier.java
public boolean isValid() throws VerificationException, NetworkAccessException { X509Certificate certificate = getCertificateChain()[0]; String subjectName = certificate.getSubjectX500Principal().getName(); try {//from ww w . j ava 2 s . c o m certificate.checkValidity(); } catch (CertificateExpiredException ignored) { return false; } catch (CertificateNotYetValidException ignored) { return false; } if (getSubjectMatchingPattern() != null && !getSubjectMatchingPattern().matcher(subjectName).matches()) { return false; } if (keyUsageRestrictions != null && !KeyUsageHelper.validateKeyUsage(certificate, keyUsageRestrictions)) { return false; } if (crlHelper != null && !crlHelper.isValid(certificate)) { logger.warn("CRL validation failed"); return false; } if (ocspHelper != null && !ocspHelper.isValid(certificate)) { logger.warn("OCSP validation failed"); return false; } return true; }
From source file:org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthorityFragment.java
private boolean editAuthority(final String old_alias, final String new_alias, final int position, final String uri) { try {/*from ww w . jav a 2 s. c om*/ final KeyStore ks = SettingsSmartPGPAuthoritiesActivity.readKeystore(getContext()); if (ks == null) { throw new KeyStoreException("no keystore found"); } Certificate old_cert = null; if (old_alias != null) { old_cert = ks.getCertificate(old_alias); ks.deleteEntry(old_alias); mAuthorities.remove(old_alias); mAdapter.notifyItemRemoved(position); } Certificate new_cert = null; if (uri == null) { new_cert = old_cert; } else { final InputStream fis = getContext().getContentResolver().openInputStream(Uri.parse(uri)); final CertificateFactory cf = CertificateFactory.getInstance("X.509"); new_cert = cf.generateCertificate(fis); if (!(new_cert instanceof X509Certificate)) { Notify.create(getActivity(), "Invalid certificate", Notify.LENGTH_LONG, Notify.Style.ERROR) .show(); return false; } fis.close(); } if (new_alias == null || new_cert == null) { Notify.create(getActivity(), "Missing alias or certificate", Notify.LENGTH_LONG, Notify.Style.ERROR) .show(); return false; } final X509Certificate x509cert = (X509Certificate) new_cert; x509cert.checkValidity(); ks.setCertificateEntry(new_alias, x509cert); SettingsSmartPGPAuthoritiesActivity.writeKeystore(getContext(), ks); mAuthorities.add(new_alias); mAdapter.notifyItemInserted(mAuthorities.size() - 1); return true; } catch (IOException e) { Notify.create(getActivity(), "failed to open certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } catch (CertificateException e) { Notify.create(getActivity(), "invalid certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } catch (KeyStoreException e) { Notify.create(getActivity(), "invalid keystore (" + e.getMessage() + ")", Notify.LENGTH_LONG, Notify.Style.ERROR).show(); } return false; }
From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java
@Override public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer, PrivateKey signingKey, Date notAfter) { signer = (signingKey == null ? signer : subjectDn); signingKey = (signingKey == null ? keys.getPrivate() : signingKey); EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(), subjectDn.toString()).info(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4) .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000)))); certGen.setIssuerDN(signer);/*from w ww . jav a 2 s .co m*/ certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); try { certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keys.getPublic())); } catch (InvalidKeyException e) { LOG.error("Error adding subject key identifier extension.", e); } Calendar cal = Calendar.getInstance(); certGen.setNotBefore(cal.getTime()); certGen.setNotAfter(notAfter); certGen.setSubjectDN(subjectDn); certGen.setPublicKey(keys.getPublic()); certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM); try { X509Certificate cert = certGen.generate(signingKey, PROVIDER); cert.checkValidity(); return cert; } catch (Exception e) { LOG.fatal(e, e); return null; } }
From source file:org.alfresco.web.scripts.servlet.X509ServletFilterBase.java
private boolean validCert(X509Certificate[] certs) { /*/*from w w w . j a va 2s . c o m*/ * If the cert is null then the it's not valid. */ if (certs == null) { return false; } /* * Get the first certificate in the chain. The first certificate is the client certificate. */ X509Certificate cert = certs[0]; try { /* * check the certificate has not expired. */ if (logger.isDebugEnabled()) { logger.debug("Checking cert is valid"); } cert.checkValidity(); } catch (Exception e) { logger.error("Cert is invalid", e); return false; } X500Principal x500Principal = cert.getSubjectX500Principal(); String name = x500Principal.getName(); /* * Cert contains is an optional check */ if (this.certContains == null) { return true; } /* * Check that the cert contains the specified value. */ if (name.contains(this.certContains)) { if (logger.isDebugEnabled()) { logger.debug("Cert: " + name + " contains: " + this.certContains); } return true; } else { logger.error("Cert: " + name + " does not contain: " + this.certContains); return false; } }