List of usage examples for java.security.cert X509Certificate getNotAfter
public abstract Date getNotAfter();
From source file:net.solarnetwork.node.setup.impl.DefaultSetupService.java
@Override public InstructionState processInstruction(Instruction instruction) { if (!INSTRUCTION_TOPIC_RENEW_CERTIFICATE.equalsIgnoreCase(instruction.getTopic())) { return null; }/*from w w w . jav a 2 s .c o m*/ PKIService pki = pkiService; if (pki == null) { return null; } String[] certParts = instruction.getAllParameterValues(INSTRUCTION_PARAM_CERTIFICATE); if (certParts == null) { log.warn("Certificate not provided with renew instruction"); return InstructionState.Declined; } String cert = org.springframework.util.StringUtils.arrayToDelimitedString(certParts, ""); log.debug("Got certificate renewal instruction with certificate data: {}", cert); try { pki.saveNodeSignedCertificate(cert); if (log.isInfoEnabled()) { X509Certificate nodeCert = pki.getNodeCertificate(); log.info("Installed node certificate {}, valid to {}", nodeCert.getSerialNumber(), nodeCert.getNotAfter()); } return InstructionState.Completed; } catch (CertificateException e) { log.error("Failed to install renewed certificate", e); } return null; }
From source file:cl.nic.dte.util.XMLUtil.java
/** * Verifica si una firma XML embedida es válida según define * el estándar XML Signature (<a * href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core * Validation</a>), y si el certificado era válido en la fecha dada. * <p>//w ww . j av a2 s . c o m * * Esta rutina <b>NO</b> verifica si el certificado embedido en * <KeyInfo> es válido (eso debe verificarlo con la autoridad * certificadora que emitió el certificado), pero si verifica que la * llave utilizada para verificar corresponde a la contenida en el * certificado. * * @param xml * el nodo <Signature> * @param date * una fecha en la que se verifica la validez del certificado * @return el resultado de la verificación * * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext) * @see cl.nic.dte.VerifyResult * @see cl.nic.dte.extension.DTEDefTypeExtensionHandler * @see #getCertificate(XMLSignature) */ public static VerifyResult verifySignature(Node xml, Date date) { try { XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); KeyValueKeySelector ksel = new KeyValueKeySelector(); DOMValidateContext valContext = new DOMValidateContext(ksel, xml); // Unmarshal the signature XMLSignature signature = fac.unmarshalXMLSignature(valContext); X509Certificate x509 = getCertificate(signature); // Verifica que un certificado bien embedido if (x509 == null) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NO509"))); } try { // Valida que en la fecha dada el certificado era va'lido x509.checkValidity(date); } catch (CertificateExpiredException e) { String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID"); message = message.replaceAll("%1", DateFormat.getDateInstance().format(date)); message = message.replaceAll("%2", DateFormat.getDateInstance().format(x509.getNotBefore())); message = message.replaceAll("%3", DateFormat.getDateInstance().format(x509.getNotAfter())); return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message)); } catch (CertificateNotYetValidException e) { String message = Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_NOTVALID"); message = message.replaceAll("%1", DateFormat.getDateInstance().format(date)); message = message.replaceAll("%2", DateFormat.getDateInstance().format(x509.getNotBefore())); message = message.replaceAll("%3", DateFormat.getDateInstance().format(x509.getNotAfter())); return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, message)); } return (verifySignature(signature, valContext)); } catch (MarshalException e1) { return (new VerifyResult(VerifyResult.XML_SIGNATURE_WRONG, false, Utilities.verificationLabels.getString("XML_SIGNATURE_ERROR_UNMARSHAL") + ": " + e1.getMessage())); } }
From source file:gov.nist.toolkit.soap.axis2.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() throws IOException { try {/* ww w.j a va 2s .co m*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.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.debug(" Certificate " + (c + 1) + ":"); LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LOG.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); throw new IOException("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { LOG.error(e.getMessage(), e); throw new IOException("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { LOG.error(e.getMessage(), e); throw new IOException("Key management exception: " + e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new IOException("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:edu.vt.middleware.crypt.KeyStoreCli.java
/** * Prints a string representation of the given certificate to STDOUT. For an * X.509 certificate, prints important fields. * * @param cert Certificate to print.//from www . j a v a 2 s . com * * @throws Exception On print errors. */ protected void printCertificate(final Certificate cert) throws Exception { if (cert instanceof X509Certificate) { final X509Certificate xCert = (X509Certificate) cert; final byte[] encodedCert = xCert.getEncoded(); System.out.println("Subject: " + xCert.getSubjectDN()); System.out.println("Issuer: " + xCert.getIssuerDN()); System.out.println("Serial: " + hexConv.fromBytes(xCert.getSerialNumber().toByteArray())); System.out.println("Valid not before: " + xCert.getNotBefore()); System.out.println("Valid not after: " + xCert.getNotAfter()); System.out.println("MD5 fingerprint: " + md5.digest(encodedCert, hexConv)); System.out.println("SHA1 fingerprint: " + sha1.digest(encodedCert, hexConv)); } else { System.out.println(cert); } }
From source file:AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {//ww w. j av a2 s . co m KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { System.out.println("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; System.out.println(" Certificate " + (c + 1) + ":"); System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); System.out.println("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:org.ejbca.core.ejb.ocsp.OcspKeyRenewalSessionBean.java
/** * //from www . j av a2s.c o m * * @param signerSubjectDN signerSubjectDN subject DN of the signing key to be renewed. The string "all" will result in all keys being renewed * @param safetyMargin the number of seconds before actual expiration that a keystore should be renewed * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist. * @throws InvalidKeyException if the public key in the tokenAndChain can not be used to verify a string signed by the private key, because the key * is wrong or the signature operation fails for other reasons such as a NoSuchAlgorithmException or SignatureException. */ private synchronized void renewKeyStores(String signerSubjectDN, long safetyMargin) throws InvalidKeyException, CryptoTokenOfflineException { //Cancel all running timers cancelTimers(); try { final EjbcaWS ejbcaWS = getEjbcaWS(); if (ejbcaWS == null) { if (log.isDebugEnabled()) { log.debug( "Could not locate a suitable web service for automatic OCSP key/certificate renewal."); } return; } final X500Principal target; try { target = signerSubjectDN.trim().equalsIgnoreCase(RENEW_ALL_KEYS) ? null : new X500Principal(signerSubjectDN); } catch (IllegalArgumentException e) { log.error(intres.getLocalizedMessage("ocsp.rekey.triggered.dn.not.valid", signerSubjectDN)); return; } final StringBuffer matched = new StringBuffer(); final StringBuffer unMatched = new StringBuffer(); for (final OcspSigningCacheEntry ocspSigningCacheEntry : OcspSigningCache.INSTANCE.getEntries()) { // Only perform renewal for non CA signing key OCSP signers if (!ocspSigningCacheEntry.isUsingSeparateOcspSigningCertificate()) { continue; } final X509Certificate ocspSigningCertificate = ocspSigningCacheEntry.getOcspSigningCertificate(); final long timeLeftBeforeRenewal = ocspSigningCertificate.getNotAfter().getTime() - new Date().getTime(); if (timeLeftBeforeRenewal < (1000 * safetyMargin)) { final X500Principal src = ocspSigningCertificate.getSubjectX500Principal(); if (target != null && !src.equals(target)) { unMatched.append(" '" + src.getName() + '\''); continue; } matched.append(" '" + ocspSigningCertificate.getIssuerX500Principal().getName() + '\''); try { renewKeyStore(ejbcaWS, ocspSigningCacheEntry); } catch (KeyRenewalFailedException e) { String msg = intres.getLocalizedMessage("ocsp.rekey.failed.unknown.reason", target, e.getLocalizedMessage()); log.error(msg, e); continue; } } } if (matched.length() < 1 && target != null) { log.error(intres.getLocalizedMessage("ocsp.rekey.triggered.dn.not.existing", target.getName(), unMatched)); return; } log.info(intres.getLocalizedMessage("ocsp.rekey.triggered", matched)); } finally { //Set new timer to run, even if something breaks. addTimer(OcspConfiguration.getRekeyingUpdateTimeInSeconds()); } }
From source file:org.wso2.carbon.identity.certificateauthority.dao.CertificateDAO.java
/** * adds a public certificate to the database * * @param serial serial number of the certificate * @param tenantID id of the tenant tenant who issued the certificate * @return//from www . j a v a 2s . c om */ public void addCertificate(String serial, X509Certificate certificate, int tenantID, String username, String userStoreDomain) throws CaException { Connection connection = null; Date requestDate = new Date(); String sql = null; PreparedStatement prepStmt = null; try { Date expiryDate = certificate.getNotAfter(); log.debug("adding public certificate file to database"); connection = JDBCPersistenceManager.getInstance().getDBConnection(); sql = "INSERT INTO CA_CERTIFICATE_STORE (SERIAL_NO,PUBLIC_CERTIFICATE,STATUS,ISSUED_DATE,EXPIRY_DATE,TENANT_ID,USER_NAME,UM_DOMAIN_NAME) VALUES (?,?,?,?,?,?,?,?) "; prepStmt = connection.prepareStatement(sql); prepStmt.setString(1, serial); prepStmt.setBlob(2, new ByteArrayInputStream(certificate.getEncoded())); prepStmt.setString(3, CertificateStatus.ACTIVE.toString()); prepStmt.setTimestamp(4, new Timestamp(requestDate.getTime())); prepStmt.setTimestamp(5, new Timestamp(expiryDate.getTime())); prepStmt.setInt(6, tenantID); prepStmt.setString(7, username); prepStmt.setString(8, userStoreDomain); prepStmt.execute(); connection.commit(); } catch (IdentityException e) { String errorMsg = "Error when getting an Identity Persistence Store instance."; log.error(errorMsg, e); throw new CaException(errorMsg, e); } catch (SQLException e) { log.error("Error when executing the SQL : " + sql); log.error(e.getMessage(), e); } catch (CertificateEncodingException e) { log.error("Error encoding certificate"); } finally { IdentityDatabaseUtil.closeAllConnections(connection, null, prepStmt); } }
From source file:br.gov.serpro.cert.AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/*from www. ja v a 2s . c o m*/ // KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; /* if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String)aliases.nextElement(); Certificate[] certs = keystore.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.debug(" Certificate " + (c + 1) + ":"); LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore() ); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } */ if (this.truststoreUrls != null) { KeyStore keystore = createKeyStore(this.truststoreUrls, this.truststorePasswords); if (LOG.isDebugEnabled()) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); LOG.debug("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; LOG.debug(" Subject DN: " + cert.getSubjectDN()); LOG.debug(" Signature Algorithm: " + cert.getSigAlgName()); LOG.debug(" Valid from: " + cert.getNotBefore()); LOG.debug(" Valid until: " + cert.getNotAfter()); LOG.debug(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(null, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:com.utest.webservice.client.rest.AuthSSLProtocolSocketFactory.java
@SuppressWarnings("unchecked") private SSLContext createSSLContext() { try {/*from w ww .ja va 2s. co m*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); if (true) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { System.out.println("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; System.out.println(" Certificate " + (c + 1) + ":"); System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); if (true) { Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); System.out.println("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { System.out.println(e.getMessage()); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { System.out.println(e.getMessage()); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { System.out.println(e.getMessage()); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:org.apache.nifi.toolkit.tls.util.TlsHelperTest.java
@Test public void testIssueCert() throws IOException, CertificateException, NoSuchAlgorithmException, OperatorCreationException, NoSuchProviderException, InvalidKeyException, SignatureException { X509Certificate issuer = loadCertificate( new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.crt"))); KeyPair issuerKeyPair = loadKeyPair( new InputStreamReader(getClass().getClassLoader().getResourceAsStream("rootCert.key"))); String dn = "CN=testIssued, O=testOrg"; KeyPair keyPair = TlsHelper.generateKeyPair(keyPairAlgorithm, keySize); X509Certificate x509Certificate = CertificateUtils.generateIssuedCertificate(dn, keyPair.getPublic(), issuer, issuerKeyPair, signingAlgorithm, days); assertEquals(dn, x509Certificate.getSubjectX500Principal().toString()); assertEquals(issuer.getSubjectX500Principal().toString(), x509Certificate.getIssuerX500Principal().toString()); assertEquals(keyPair.getPublic(), x509Certificate.getPublicKey()); Date notAfter = x509Certificate.getNotAfter(); assertTrue(notAfter.after(inFuture(days - 1))); assertTrue(notAfter.before(inFuture(days + 1))); Date notBefore = x509Certificate.getNotBefore(); assertTrue(notBefore.after(inFuture(-1))); assertTrue(notBefore.before(inFuture(1))); assertEquals(signingAlgorithm, x509Certificate.getSigAlgName()); assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm()); x509Certificate.verify(issuerKeyPair.getPublic()); }