List of usage examples for java.security.cert X509Certificate getNotAfter
public abstract Date getNotAfter();
From source file:be.fedict.trust.service.bean.HarvesterMDB.java
private void processHarvestMessage(HarvestMessage harvestMessage) { if (null == harvestMessage) { return;/* ww w.j a v a2 s .c o m*/ } String caName = harvestMessage.getCaName(); boolean update = harvestMessage.isUpdate(); String crlFilePath = harvestMessage.getCrlFile(); File crlFile = new File(crlFilePath); LOG.debug("processHarvestMessage - Don't have CA's Serial Number??"); LOG.debug("issuer: " + caName); CertificateAuthorityEntity certificateAuthority = this.certificateAuthorityDAO .findCertificateAuthority(caName); if (null == certificateAuthority) { LOG.error("unknown certificate authority: " + caName); deleteCrlFile(crlFile); return; } if (!update && Status.PROCESSING != certificateAuthority.getStatus()) { /* * Possible that another harvester instance already activated or is * processing the CA cache in the meanwhile. */ LOG.debug("CA status not marked for processing"); deleteCrlFile(crlFile); return; } Date validationDate = new Date(); X509Certificate issuerCertificate = certificateAuthority.getCertificate(); Date notAfter = issuerCertificate.getNotAfter(); if (validationDate.after(notAfter)) { LOG.info("will not update CRL cache for expired CA: " + issuerCertificate.getSubjectX500Principal()); deleteCrlFile(crlFile); return; } FileInputStream crlInputStream; try { crlInputStream = new FileInputStream(crlFile); } catch (FileNotFoundException e) { LOG.error("CRL file does not exist: " + crlFilePath); return; } X509CRL crl; try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); crl = (X509CRL) certificateFactory.generateCRL(crlInputStream); } catch (Exception e) { LOG.error("BC error: " + e.getMessage(), e); deleteCrlFile(crlFile); return; } LOG.debug("checking integrity CRL..."); boolean crlValid = CrlTrustLinker.checkCrlIntegrity(crl, issuerCertificate, validationDate); if (!crlValid) { this.auditDAO.logAudit("Invalid CRL for CA=" + caName); deleteCrlFile(crlFile); return; } BigInteger crlNumber = getCrlNumber(crl); LOG.debug("CRL number: " + crlNumber); BigInteger currentCrlNumber = this.certificateAuthorityDAO.findCrlNumber(caName); if (null != currentCrlNumber) { LOG.debug("CRL number in database: " + currentCrlNumber); } if (null != currentCrlNumber && currentCrlNumber.compareTo(crlNumber) >= 0 && certificateAuthority.getStatus() == Status.ACTIVE) { // current CRL cache is higher or equal, no update needed LOG.debug("current CA cache is new enough."); deleteCrlFile(crlFile); return; } List<RevokedCertificateEntity> revokedCertificateEntities = this.certificateAuthorityDAO .getRevokedCertificates(caName); LOG.debug("number of revoked certificates in database: " + revokedCertificateEntities.size()); Map<String, RevokedCertificateEntity> revokedCertificatesMap = new HashMap<String, RevokedCertificateEntity>(); for (RevokedCertificateEntity revokedCertificateEntity : revokedCertificateEntities) { String serialNumber = revokedCertificateEntity.getPk().getSerialNumber(); revokedCertificatesMap.put(serialNumber, revokedCertificateEntity); } LOG.debug("processing CRL... " + caName); boolean isIndirect; Enumeration revokedCertificatesEnum; try { isIndirect = isIndirectCRL(crl); revokedCertificatesEnum = getRevokedCertificatesEnum(crl); } catch (Exception e) { this.auditDAO.logAudit("Failed to parse CRL for CA=" + caName); this.failures++; throw new RuntimeException(e); } int entries = 0; if (revokedCertificatesEnum.hasMoreElements()) { /* * Split up persisting the crl entries to avoid memory issues. */ Set<X509CRLEntry> revokedCertsBatch = new HashSet<X509CRLEntry>(); X500Principal previousCertificateIssuer = crl.getIssuerX500Principal(); int added = 0; while (revokedCertificatesEnum.hasMoreElements()) { TBSCertList.CRLEntry entry = (TBSCertList.CRLEntry) revokedCertificatesEnum.nextElement(); X500Name x500name = new X500Name(previousCertificateIssuer.getName(X500Principal.RFC1779)); X509CRLEntryObject revokedCertificate = new X509CRLEntryObject(entry, isIndirect, x500name); previousCertificateIssuer = revokedCertificate.getCertificateIssuer(); revokedCertsBatch.add(revokedCertificate); added++; if (added == BATCH_SIZE) { /* * Persist batch */ this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber, crl.getIssuerX500Principal(), revokedCertificatesMap); entries += revokedCertsBatch.size(); revokedCertsBatch.clear(); added = 0; } } /* * Persist final batch */ this.certificateAuthorityDAO.updateRevokedCertificates(revokedCertsBatch, crlNumber, crl.getIssuerX500Principal(), revokedCertificatesMap); entries += revokedCertsBatch.size(); /* * Cleanup redundant CRL entries */ if (null != crlNumber) { this.certificateAuthorityDAO.removeOldRevokedCertificates(crlNumber, crl.getIssuerX500Principal().toString()); } } deleteCrlFile(crlFile); LOG.debug("CRL this update: " + crl.getThisUpdate()); LOG.debug("CRL next update: " + crl.getNextUpdate()); certificateAuthority.setStatus(Status.ACTIVE); certificateAuthority.setThisUpdate(crl.getThisUpdate()); certificateAuthority.setNextUpdate(crl.getNextUpdate()); LOG.debug("cache activated for CA: " + crl.getIssuerX500Principal() + " (entries=" + entries + ")"); }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * Method to update the certificate which matches the given alias. * * @param certificate: The base64 encoded certificate string. * @param alias : Alias of the certificate that should be retrieved. * @return ://from ww w . j av a 2 s . c o m */ public ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException { InputStream certificateStream = null; try { File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (trustStore.getCertificate(alias) == null) { log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found" + " in the trust store."); return ResponseCode.CERTIFICATE_NOT_FOUND; } //Generate the certificate from the input string. byte[] cert = (Base64.decodeBase64(certificate.getBytes(CHARSET_UTF_8))); certificateStream = new ByteArrayInputStream(cert); if (certificateStream.available() == 0) { log.error("Certificate is empty for the provided alias " + alias); return ResponseCode.INTERNAL_SERVER_ERROR; } CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE); Certificate newCertificate = certificateFactory.generateCertificate(certificateStream); X509Certificate x509Certificate = (X509Certificate) newCertificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { log.error("Could not update the certificate. The certificate expired."); return ResponseCode.CERTIFICATE_EXPIRED; } // If the certificate is not expired, delete the existing certificate and add the new cert. trustStore.deleteEntry(alias); //Store the certificate in the trust store. trustStore.setCertificateEntry(alias, newCertificate); fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); } catch (IOException e) { throw new CertificateManagementException("Error updating certificate.", e); } catch (CertificateException e) { throw new CertificateManagementException("Error generating the certificate.", e); } catch (NoSuchAlgorithmException e) { throw new CertificateManagementException("Error loading the keystore.", e); } catch (KeyStoreException e) { throw new CertificateManagementException("Error updating the certificate in the keystore.", e); } finally { closeStreams(fileOutputStream, certificateStream, localTrustStoreStream); } return ResponseCode.SUCCESS; }
From source file:com.cordys.coe.util.cgc.ssl.AuthSSLX509TrustManager.java
/** * This method checks if the certificate can be trusted. If you do not want to accept the * certificate you need to throw an exception. * * @param certificates The certificates to check. * @param sAuthType The authentication type. * * @throws CertificateException In case the certificate should not be accepted. */// w ww . j a v a 2 s.c o m public void checkClientTrusted(X509Certificate[] certificates, String sAuthType) throws CertificateException { if (m_xtmDefault != null) { if (certificates != null) { for (int c = 0; c < certificates.length; c++) { X509Certificate cert = certificates[c]; if (LOG.isInfoEnabled()) { LOG.info(" Client certificate " + (c + 1) + ":"); LOG.info(" Subject DN: " + cert.getSubjectDN()); LOG.info(" Signature Algorithm: " + cert.getSigAlgName()); LOG.info(" Valid from: " + cert.getNotBefore()); LOG.info(" Valid until: " + cert.getNotAfter()); LOG.info(" Issuer: " + cert.getIssuerDN()); } try { cert.checkValidity(); } catch (CertificateExpiredException e) { LOG.fatal("Client certificate " + cert.getSubjectDN() + " is expired."); } catch (CertificateNotYetValidException e) { LOG.fatal("Client certificate " + cert.getSubjectDN() + " is not yet valid."); } } } // Call the super to do the actual checking. m_xtmDefault.checkClientTrusted(certificates, sAuthType); } }
From source file:com.cordys.coe.util.cgc.ssl.AuthSSLX509TrustManager.java
/** * This method checks if the server certificate is trusted. * * @param certificates The list of certificates. * @param sAuthType The authentication type. * * @throws CertificateException DOCUMENTME *///from w w w. ja v a 2s . c o m public void checkServerTrusted(X509Certificate[] certificates, String sAuthType) throws CertificateException { if (m_xtmDefault != null) { if (certificates != null) { for (int c = 0; c < certificates.length; c++) { X509Certificate cert = certificates[c]; if (LOG.isInfoEnabled()) { LOG.info(" Server certificate " + (c + 1) + ":"); LOG.info(" Subject DN: " + cert.getSubjectDN()); LOG.info(" Signature Algorithm: " + cert.getSigAlgName()); LOG.info(" Valid from: " + cert.getNotBefore()); LOG.info(" Valid until: " + cert.getNotAfter()); LOG.info(" Issuer: " + cert.getIssuerDN()); } try { cert.checkValidity(); } catch (CertificateExpiredException e) { LOG.fatal("Server certificate " + cert.getSubjectDN() + " is expired."); } catch (CertificateNotYetValidException e) { LOG.fatal("Server certificate " + cert.getSubjectDN() + " is not yet valid."); } } } // Call the super to do the actual checking. m_xtmDefault.checkServerTrusted(certificates, sAuthType); } }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * To validate the current certificate and alias. * * @param alias Alias of the certificate. * @param certificate Bas64 endcoded certificated. * @return response code based on the validation *//*w w w . j a va2s . com*/ public ResponseCode validateCertificate(String alias, int tenantId, String certificate) { File trustStoreFile = new File(TRUST_STORE); ResponseCode responseCode = ResponseCode.SUCCESS; ByteArrayInputStream serverCert = null; try { localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); if (StringUtils.isNotEmpty(alias) && trustStore.containsAlias(alias + "_" + tenantId)) { responseCode = ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE; } if (responseCode != ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE) { byte[] cert = (Base64.decodeBase64(certificate.getBytes(StandardCharsets.UTF_8))); serverCert = new ByteArrayInputStream(cert); if (serverCert.available() == 0) { responseCode = ResponseCode.CERTIFICATE_NOT_FOUND; } else { CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE); while (serverCert.available() > 0) { Certificate generatedCertificate = cf.generateCertificate(serverCert); X509Certificate x509Certificate = (X509Certificate) generatedCertificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { responseCode = ResponseCode.CERTIFICATE_EXPIRED; } } } } } catch (IOException e) { log.error("I/O Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (CertificateException e) { log.error("Certificate Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("No Such Algorithm Exception while trying to load trust store while trying to check whether " + "alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("KeyStore Exception while trying to load trust store while trying to check whether alias " + alias + " exists", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(serverCert); } return responseCode; }
From source file:it.jnrpe.plugin.CheckHttp.java
private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx);//from w w w . ja v a 2 s . co m HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); List<Date> expiryDates = new ArrayList<Date>(); conn.getResponseCode(); Certificate[] certs = conn.getServerCertificates(); for (Certificate cert : certs) { X509Certificate x509 = (X509Certificate) cert; Date expiry = x509.getNotAfter(); expiryDates.add(expiry); } conn.disconnect(); Date today = new Date(); for (Date date : expiryDates) { int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)); metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null)); } }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * This method generates a certificate from a base64 encoded certificate string and add to the configured trust * store./*from www . j av a 2 s .c o m*/ * * @param base64Cert : The base 64 encoded string of the server certificate. * @param alias : The alias for the certificate. * @return : ResponseCode which matches the execution result. * * Response Codes. * SUCCESS : If certificate added successfully. * INTERNAL_SERVER_ERROR : If any internal error occurred * ALIAS_EXISTS_IN_TRUST_STORE : If the alias exists in trust store. * CERTIFICATE_EXPIRED : If the given certificate is expired. */ public ResponseCode addCertificateToTrustStore(String base64Cert, String alias) { boolean isCertExists = false; boolean expired = false; InputStream serverCert = null; try { //Decode base64 encoded certificate. byte[] cert = (Base64.decodeBase64(base64Cert.getBytes(CHARSET_UTF_8))); serverCert = new ByteArrayInputStream(cert); if (serverCert.available() == 0) { log.error("Certificate is empty for the provided alias " + alias); return ResponseCode.INTERNAL_SERVER_ERROR; } //Read the client-truststore.jks into a KeyStore. File trustStoreFile = new File(TRUST_STORE); localTrustStoreStream = new FileInputStream(trustStoreFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD); CertificateFactory cf = CertificateFactory.getInstance(CERTIFICATE_TYPE); while (serverCert.available() > 0) { Certificate certificate = cf.generateCertificate(serverCert); //Check whether the Alias exists in the trust store. if (trustStore.containsAlias(alias)) { isCertExists = true; } else { /* * If alias is not exists, check whether the certificate is expired or not. If expired set the * expired flag. * */ X509Certificate x509Certificate = (X509Certificate) certificate; if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) { expired = true; if (log.isDebugEnabled()) { log.debug("Provided certificate is expired."); } } else { //If not expired add the certificate to trust store. trustStore.setCertificateEntry(alias, certificate); } } } fileOutputStream = new FileOutputStream(trustStoreFile); trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD); responseCode = expired ? ResponseCode.CERTIFICATE_EXPIRED : isCertExists ? ResponseCode.ALIAS_EXISTS_IN_TRUST_STORE : ResponseCode.SUCCESS; } catch (CertificateException e) { log.error("Error loading certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (FileNotFoundException e) { log.error("Error reading/ writing to the certificate file.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (NoSuchAlgorithmException e) { log.error("Could not find the algorithm to load the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (UnsupportedEncodingException e) { log.error("Error retrieving certificate from String", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (KeyStoreException e) { log.error("Error reading certificate contents.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } catch (IOException e) { log.error("Error in loading the certificate.", e); responseCode = ResponseCode.INTERNAL_SERVER_ERROR; } finally { closeStreams(localTrustStoreStream, fileOutputStream, serverCert); } return responseCode; }
From source file:org.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java
/** * To get the certificate meta data information such as version expiry data * * @param certificate Relevant certificate to get certificate meta data information. * @return Certificate meta data information. *//*from w w w . jav a2 s . c om*/ private CertificateInformationDTO getCertificateMetaData(X509Certificate certificate) { CertificateInformationDTO certificateInformation = new CertificateInformationDTO(); certificateInformation .setStatus(certificate.getNotAfter().getTime() > System.currentTimeMillis() ? "Active" : "Expired"); certificateInformation.setFrom(certificate.getNotBefore().toString()); certificateInformation.setTo(certificate.getNotAfter().toString()); certificateInformation.setSubject(certificate.getSubjectDN().toString()); certificateInformation.setVersion(String.valueOf(certificate.getVersion())); return certificateInformation; }
From source file:com.otterca.persistence.entity.X509CertificateEntity.java
/** * Cache values within certificate. They should never be set directly and * the actual values in the database should be created via triggers. * /*from ww w .j a va 2 s. c o m*/ * @param cert */ protected final void cacheAttributes(X509Certificate cert) throws CertificateEncodingException, IOException { serialNumber = cert.getSerialNumber(); certificate = cert.getEncoded(); subject = cert.getSubjectDN().getName(); issuer = cert.getIssuerDN().getName(); notBefore = cert.getNotBefore(); notAfter = cert.getNotAfter(); //name = x509CertUtil.getName(cert); //fingerprint = x509CertUtil.getFingerprint(cert); //certHash = x509CertUtil.getCertificateHash(cert); //iHash = x509CertUtil.getIHash(cert); //sHash = x509CertUtil.getSHash(cert); //akidHash = x509CertUtil.getAkidHash(cert); //skidHash = x509CertUtil.getSkidHash(cert); }
From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeRequestTest.java
public void test01CrmfHttpOkUser() throws Exception { log.debug(">test01CrmfHttpOkUser()"); byte[] nonce = CmpMessageHelper.createSenderNonce(); byte[] transid = CmpMessageHelper.createSenderNonce(); // We should be able to back date the start time when allow validity // override is enabled in the certificate profile Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_WEEK, -1); cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds // in validity Date notBefore = cal.getTime(); cal.add(Calendar.DAY_OF_WEEK, 3); cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds // in validity Date notAfter = cal.getTime(); // In this we also test validity override using notBefore and notAfter // from above // In this test userDN contains special, escaped characters to verify // that that works with CMP RA as well PKIMessage one = genCertReq(issuerDN, userDN, keys, cacert, nonce, transid, true, null, notBefore, notAfter, null);//from w w w. j a v a2 s . c o m PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, 567); assertNotNull(req); int reqId = req.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue(); ByteArrayOutputStream bao = new ByteArrayOutputStream(); DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); byte[] ba = bao.toByteArray(); // Send request and receive response byte[] resp = sendCmpHttp(ba, 200); checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, PBEPASSWORD); X509Certificate cert = checkCmpCertRepMessage(userDN, cacert, resp, reqId); // Check that validity override works assertTrue(cert.getNotBefore().equals(notBefore)); assertTrue(cert.getNotAfter().equals(notAfter)); String altNames = CertTools.getSubjectAlternativeName(cert); assertTrue(altNames.indexOf("upn=fooupn@bar.com") != -1); assertTrue(altNames.indexOf("rfc822name=fooemail@bar.com") != -1); // Send a confirm message to the CA String hash = "foo123"; PKIMessage confirm = genCertConfirm(userDN, cacert, nonce, transid, hash, reqId); assertNotNull(confirm); PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, 567); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(req1); ba = bao.toByteArray(); // Send request and receive response resp = sendCmpHttp(ba, 200); checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, PBEPASSWORD); checkCmpPKIConfirmMessage(userDN, cacert, resp); // Now revoke the bastard using the CMPv1 reason code! PKIMessage rev = genRevReq(issuerDN, userDN, cert.getSerialNumber(), cacert, nonce, transid, false); PKIMessage revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567); assertNotNull(revReq); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(revReq); ba = bao.toByteArray(); // Send request and receive response resp = sendCmpHttp(ba, 200); checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, PBEPASSWORD); checkCmpRevokeConfirmMessage(issuerDN, userDN, cert.getSerialNumber(), cacert, resp, true); int reason = checkRevokeStatus(issuerDN, cert.getSerialNumber()); assertEquals(reason, RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE); // Create a revocation request for a non existing cert, should fail! rev = genRevReq(issuerDN, userDN, new BigInteger("1"), cacert, nonce, transid, true); revReq = protectPKIMessage(rev, false, PBEPASSWORD, 567); assertNotNull(revReq); bao = new ByteArrayOutputStream(); out = new DEROutputStream(bao); out.writeObject(revReq); ba = bao.toByteArray(); // Send request and receive response resp = sendCmpHttp(ba, 200); checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, PBEPASSWORD); checkCmpRevokeConfirmMessage(issuerDN, userDN, cert.getSerialNumber(), cacert, resp, false); log.debug("<test01CrmfHttpOkUser()"); }