Java Code Examples for java.security.cert.X509Certificate#getNotAfter()
The following examples show how to use
java.security.cert.X509Certificate#getNotAfter() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CertificateUtils.java From freehealth-connector with GNU Affero General Public License v3.0 | 7 votes |
public static X509Certificate generateCert(PublicKey rqPubKey, BigInteger serialNr, Credential cred) throws TechnicalConnectorException { try { X509Certificate cert = cred.getCertificate(); X500Principal principal = cert.getSubjectX500Principal(); Date notBefore = cert.getNotBefore(); Date notAfter = cert.getNotAfter(); X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(principal, serialNr, notBefore, notAfter, principal, rqPubKey); int keyUsageDetails = 16 + 32; builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageDetails)); ContentSigner signer = (new JcaContentSignerBuilder(cert.getSigAlgName())).build(cred.getPrivateKey()); X509CertificateHolder holder = builder.build(signer); return (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(holder); } catch (OperatorCreationException | IOException | CertificateException ex) { throw new IllegalArgumentException(ex); } }
Example 2
Source File: X509Utils.java From Cake-VPN with GNU General Public License v2.0 | 6 votes |
public static String getCertificateValidityString(X509Certificate cert, Resources res) { try { cert.checkValidity(); } catch (CertificateExpiredException ce) { return "EXPIRED: "; } catch (CertificateNotYetValidException cny) { return "NOT YET VALID: "; } Date certNotAfter = cert.getNotAfter(); Date now = new Date(); long timeLeft = certNotAfter.getTime() - now.getTime(); // Time left in ms // More than 72h left, display days // More than 3 months display months if (timeLeft > 90l * 24 * 3600 * 1000) { long months = getMonthsDifference(now, certNotAfter); return res.getString(R.string.months_left, months); } else if (timeLeft > 72 * 3600 * 1000) { long days = timeLeft / (24 * 3600 * 1000); return res.getString(R.string.days_left, days); } else { long hours = timeLeft / (3600 * 1000); return res.getString(R.string.hours_left, hours); } }
Example 3
Source File: CryptoTest.java From athenz with Apache License 2.0 | 6 votes |
@Test public void testGenerateX509Certificate() throws IOException { Path path = Paths.get("src/test/resources/valid.csr"); String certStr = new String(Files.readAllBytes(path)); PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(certStr); X509Certificate caCertificate = Crypto.loadX509Certificate(ecPublicX509Cert); PrivateKey caPrivateKey = Crypto.loadPrivateKey(privateEncryptedKey, encryptedKeyPassword); X509Certificate cert = Crypto.generateX509Certificate(certReq, caPrivateKey, caCertificate, 600, false); assertNotNull(cert); assertEquals(cert.getIssuerX500Principal().getName(), "CN=athenz.syncer,O=My Test Company,L=Sunnyvale,ST=CA,C=US"); Date notAfter = cert.getNotAfter(); long diff = notAfter.getTime() - System.currentTimeMillis(); assertTrue(diff <= 600 * 60 * 1000); // convert minutes to milliseconds }
Example 4
Source File: CertificatePriorityComparator.java From cwac-netsecurity with Apache License 2.0 | 6 votes |
@Override public int compare(X509Certificate lhs, X509Certificate rhs) { int result; boolean lhsSelfSigned = lhs.getSubjectDN().equals(lhs.getIssuerDN()); boolean rhsSelfSigned = rhs.getSubjectDN().equals(rhs.getIssuerDN()); // Self-issued before not self-issued to avoid trying bridge certs first. if (lhsSelfSigned != rhsSelfSigned) { return rhsSelfSigned ? 1 : -1; } // Strength descending. result = compareStrength(rhs, lhs); if (result != 0) { return result; } // notAfter descending. Date lhsNotAfter = lhs.getNotAfter(); Date rhsNotAfter = rhs.getNotAfter(); result = rhsNotAfter.compareTo(lhsNotAfter); if (result != 0) { return result; } // notBefore descending. Date lhsNotBefore = lhs.getNotBefore(); Date rhsNotBefore = rhs.getNotBefore(); return rhsNotBefore.compareTo(lhsNotBefore); }
Example 5
Source File: X509Utils.java From Cybernet-VPN with GNU General Public License v3.0 | 6 votes |
public static String getCertificateValidityString(X509Certificate cert, Resources res) { try { cert.checkValidity(); } catch (CertificateExpiredException ce) { return "EXPIRED: "; } catch (CertificateNotYetValidException cny) { return "NOT YET VALID: "; } Date certNotAfter = cert.getNotAfter(); Date now = new Date(); long timeLeft = certNotAfter.getTime() - now.getTime(); // Time left in ms // More than 72h left, display days // More than 3 months display months if (timeLeft > 90l * 24 * 3600 * 1000) { long months = getMonthsDifference(now, certNotAfter); return res.getString(R.string.months_left, months); } else if (timeLeft > 72 * 3600 * 1000) { long days = timeLeft / (24 * 3600 * 1000); return res.getString(R.string.days_left, days); } else { long hours = timeLeft / (3600 * 1000); return res.getString(R.string.hours_left, hours); } }
Example 6
Source File: TlsHelperTest.java From localization_nifi with Apache License 2.0 | 6 votes |
@Test public void testGenerateSelfSignedCert() throws GeneralSecurityException, IOException, OperatorCreationException { String dn = "CN=testDN,O=testOrg"; X509Certificate x509Certificate = CertificateUtils.generateSelfSignedX509Certificate(TlsHelper.generateKeyPair(keyPairAlgorithm, keySize), dn, signingAlgorithm, days); 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(dn, x509Certificate.getIssuerX500Principal().getName()); assertEquals(signingAlgorithm, x509Certificate.getSigAlgName()); assertEquals(keyPairAlgorithm, x509Certificate.getPublicKey().getAlgorithm()); x509Certificate.checkValidity(); }
Example 7
Source File: EntityCertificate.java From FairEmail with GNU General Public License v3.0 | 6 votes |
public static EntityCertificate fromJSON(JSONObject json) throws JSONException, CertificateException, NoSuchAlgorithmException { EntityCertificate certificate = new EntityCertificate(); // id certificate.intermediate = json.optBoolean("intermediate"); certificate.email = json.getString("email"); certificate.data = json.getString("data"); X509Certificate cert = certificate.getCertificate(); certificate.fingerprint = getFingerprint(cert); certificate.subject = getSubject(cert); Date after = cert.getNotBefore(); Date before = cert.getNotAfter(); certificate.after = (after == null ? null : after.getTime()); certificate.before = (before == null ? null : before.getTime()); return certificate; }
Example 8
Source File: EntityCertificate.java From FairEmail with GNU General Public License v3.0 | 6 votes |
static EntityCertificate from(X509Certificate certificate, boolean intermediate, String email) throws CertificateEncodingException, NoSuchAlgorithmException { EntityCertificate record = new EntityCertificate(); record.fingerprint = getFingerprint(certificate); record.intermediate = intermediate; record.email = email; record.subject = getSubject(certificate); Date after = certificate.getNotBefore(); Date before = certificate.getNotAfter(); record.after = (after == null ? null : after.getTime()); record.before = (before == null ? null : before.getTime()); record.data = Base64.encodeToString(certificate.getEncoded(), Base64.NO_WRAP); return record; }
Example 9
Source File: X509Cert.java From xipki with Apache License 2.0 | 5 votes |
public X509Cert(X509Certificate cert, byte[] encoded) { this.bcInstance = null; this.jceInstance = Args.notNull(cert, "cert"); this.encoded = encoded; this.notBefore = cert.getNotBefore(); this.notAfter = cert.getNotAfter(); this.serialNumber = cert.getSerialNumber(); this.issuer = X500Name.getInstance(cert.getIssuerX500Principal().getEncoded()); this.subject = X500Name.getInstance(cert.getSubjectX500Principal().getEncoded()); this.selfSigned = subject.equals(issuer); }
Example 10
Source File: CertificateMetas.java From apk-parser with BSD 2-Clause "Simplified" License | 5 votes |
public static CertificateMeta from(X509Certificate certificate) throws CertificateEncodingException { byte[] bytes = certificate.getEncoded(); String certMd5 = md5Digest(bytes); String publicKeyString = byteToHexString(bytes); String certBase64Md5 = md5Digest(publicKeyString); return new CertificateMeta( certificate.getSigAlgName().toUpperCase(), certificate.getSigAlgOID(), certificate.getNotBefore(), certificate.getNotAfter(), bytes, certBase64Md5, certMd5); }
Example 11
Source File: X509Utils.java From SimpleOpenVpn-Android with Apache License 2.0 | 5 votes |
public static String getCertificateValidityString(X509Certificate cert, Resources res) { try { cert.checkValidity(); } catch (CertificateExpiredException ce) { return "EXPIRED: "; } catch (CertificateNotYetValidException cny) { return "NOT YET VALID: "; } Date certNotAfter = cert.getNotAfter(); Date now = new Date(); long timeLeft = certNotAfter.getTime() - now.getTime(); // Time left in ms // More than 72h left, display days // More than 3 months display months if (timeLeft > 90l* 24 * 3600 * 1000) { long months = getMonthsDifference(now, certNotAfter); return res.getString(R.string.months_left, months); } else if (timeLeft > 72 * 3600 * 1000) { long days = timeLeft / (24 * 3600 * 1000); return res.getString(R.string.days_left, days); } else { long hours = timeLeft / (3600 * 1000); return res.getString(R.string.hours_left, hours); } }
Example 12
Source File: PeriodValidator.java From signer with GNU Lesser General Public License v3.0 | 5 votes |
public Date valDate(X509Certificate x509) throws CertificateValidatorException { try { if (x509 != null){ x509.checkValidity(); }else{ throw new CertificateValidatorException(coreMessagesBundle.getString("error.invalid.certificate")); } } catch (Exception e) { Format formatter = new SimpleDateFormat("dd.MM.yyyy"); throw new CertificateValidatorException(coreMessagesBundle.getString("error.certificate.out.date", formatter.format(x509.getNotBefore()), formatter.format(x509.getNotAfter())), e); } return x509.getNotAfter(); }
Example 13
Source File: X509Utils.java From EasyVPN-Free with GNU General Public License v3.0 | 5 votes |
public static String getCertificateValidityString(X509Certificate cert, Resources res) { try { cert.checkValidity(); } catch (CertificateExpiredException ce) { return "EXPIRED: "; } catch (CertificateNotYetValidException cny) { return "NOT YET VALID: "; } Date certNotAfter = cert.getNotAfter(); Date now = new Date(); long timeLeft = certNotAfter.getTime() - now.getTime(); // Time left in ms // More than 72h left, display days // More than 3 months display months if (timeLeft > 90l* 24 * 3600 * 1000) { long months = getMonthsDifference(now, certNotAfter); return res.getString(R.string.months_left, months); } else if (timeLeft > 72 * 3600 * 1000) { long days = timeLeft / (24 * 3600 * 1000); return res.getString(R.string.days_left, days); } else { long hours = timeLeft / (3600 * 1000); return res.getString(R.string.hours_left, hours); } }
Example 14
Source File: X509CertificateShortInfo.java From oxTrust with MIT License | 5 votes |
public X509CertificateShortInfo(String alias, X509Certificate cert) { this.alias = alias; if (cert.getIssuerDN() != null) issuer = cert.getIssuerDN().getName(); if (cert.getSubjectDN() != null) subject = cert.getSubjectDN().getName(); algorithm = cert.getSigAlgName(); notBeforeDatetime = cert.getNotBefore(); notAfterDatetime = cert.getNotAfter(); updateViewStyle(); }
Example 15
Source File: CertModel.java From Jpom with MIT License | 4 votes |
/** * 解析证书 * * @param key zip里面文件 * @param file 证书文件 * @return 处理后的json */ public static JSONObject decodeCert(String file, String key) { if (file == null) { return null; } if (!FileUtil.exist(file)) { return null; } InputStream inputStream = null; try { inputStream = ResourceUtil.getStream(key); PrivateKey privateKey = PemUtil.readPemPrivateKey(inputStream); IoUtil.close(inputStream); inputStream = ResourceUtil.getStream(file); PublicKey publicKey = PemUtil.readPemPublicKey(inputStream); IoUtil.close(inputStream); RSA rsa = new RSA(privateKey, publicKey); String encryptStr = rsa.encryptBase64(KEY, KeyType.PublicKey); String decryptStr = rsa.decryptStr(encryptStr, KeyType.PrivateKey); if (!KEY.equals(decryptStr)) { throw new JpomRuntimeException("证书和私钥证书不匹配"); } } finally { IoUtil.close(inputStream); } try { inputStream = ResourceUtil.getStream(file); // 创建证书对象 X509Certificate oCert = (X509Certificate) KeyUtil.readX509Certificate(inputStream); //到期时间 Date expirationTime = oCert.getNotAfter(); //生效日期 Date effectiveTime = oCert.getNotBefore(); //域名 String name = oCert.getSubjectDN().getName(); int i = name.indexOf("="); String domain = name.substring(i + 1); JSONObject jsonObject = new JSONObject(); jsonObject.put("expirationTime", expirationTime.getTime()); jsonObject.put("effectiveTime", effectiveTime.getTime()); jsonObject.put("domain", domain); jsonObject.put("pemPath", file); jsonObject.put("keyPath", key); return jsonObject; } catch (Exception e) { DefaultSystemLog.getLog().error(e.getMessage(), e); } finally { IoUtil.close(inputStream); } return null; }
Example 16
Source File: X509CertUtils.java From MaxKey with Apache License 2.0 | 4 votes |
/** * Renew a self-signed X509 Version 1 certificate. * * @return The renewed certificate * @param oldCert * old certificate * @param iValidity * Validity period of certificate in days to add to the old * cert's expiry date, or current time if the certificate has * expired * @param publicKey * Public part of key pair * @param privateKey * Private part of key pair * @throws CryptoException * If there was a problem generating the certificate */ public static X509Certificate renewCert(X509Certificate oldCert, int iValidity, PublicKey publicKey, PrivateKey privateKey) throws CryptoException { // Get an X509 Version 1 Certificate generator X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); // Load the generator with generation parameters // Valid before and after dates now to iValidity days in the future from // now or existing expiry date Date now = new Date(); Date oldExpiry = oldCert.getNotAfter(); if (oldExpiry == null || oldExpiry.before(now)) { oldExpiry = now; } certGen.setNotBefore(now); certGen.setNotAfter(new Date(oldExpiry.getTime() + ((long) iValidity * 24 * 60 * 60 * 1000))); // Set the public key certGen.setPublicKey(publicKey); // Set the algorithm certGen.setSignatureAlgorithm(oldCert.getSigAlgName()); // Set the serial number certGen.setSerialNumber(generateX509SerialNumber()); try { // Set the issuer distinguished name // TODO: verify/force self-signedness certGen.setIssuerDN(PrincipalUtil.getIssuerX509Principal(oldCert)); // Set the subject distinguished name (same as issuer for our // purposes) certGen.setSubjectDN(PrincipalUtil.getSubjectX509Principal(oldCert)); // Generate an X.509 certificate, based on the current issuer and // subject return certGen.generate(privateKey, "BC"); } // Something went wrong catch (GeneralSecurityException ex) { throw new CryptoException("Certificate generation failed.", ex); } }
Example 17
Source File: KeyStoresTestCase.java From wildfly-core with GNU Lesser General Public License v2.1 | 4 votes |
@Test public void testGenerateKeyPair() throws Exception { addKeyStore(); try { int numAliasesBefore = readAliases().size(); ModelNode operation = new ModelNode(); operation.get(ClientConstants.OP_ADDR).add("subsystem", "elytron").add("key-store", KEYSTORE_NAME); operation.get(ClientConstants.OP).set(ElytronDescriptionConstants.GENERATE_KEY_PAIR); operation.get(ElytronDescriptionConstants.ALIAS).set("bsmith"); operation.get(ElytronDescriptionConstants.ALGORITHM).set("RSA"); operation.get(ElytronDescriptionConstants.KEY_SIZE).set(1024); operation.get(ElytronDescriptionConstants.VALIDITY).set(365); operation.get(ElytronDescriptionConstants.SIGNATURE_ALGORITHM).set("SHA256withRSA"); operation.get(ElytronDescriptionConstants.DISTINGUISHED_NAME).set("CN=bob smith, OU=jboss, O=red hat, L=raleigh, ST=north carolina, C=us"); ModelNode extensions = new ModelNode(); extensions.add(getExtension(false, "ExtendedKeyUsage", "clientAuth")); extensions.add(getExtension(true, "KeyUsage", "digitalSignature")); extensions.add(getExtension(false, "SubjectAlternativeName", "email:[email protected],DNS:bobsmith.example.com")); operation.get(ElytronDescriptionConstants.EXTENSIONS).set(extensions); operation.get(CredentialReference.CREDENTIAL_REFERENCE).get(CredentialReference.CLEAR_TEXT).set(KEY_PASSWORD); assertSuccess(services.executeOperation(operation)); assertEquals(numAliasesBefore + 1, readAliases().size()); ModelNode newAlias = readAlias("bsmith"); assertEquals(KeyStore.PrivateKeyEntry.class.getSimpleName(), newAlias.get(ElytronDescriptionConstants.ENTRY_TYPE).asString()); assertEquals(1, newAlias.get(ElytronDescriptionConstants.CERTIFICATE_CHAIN).asList().size()); ServiceName serviceName = Capabilities.KEY_STORE_RUNTIME_CAPABILITY.getCapabilityServiceName(KEYSTORE_NAME); KeyStore keyStore = (KeyStore) services.getContainer().getService(serviceName).getValue(); assertNotNull(keyStore); X509Certificate certificate = (X509Certificate) keyStore.getCertificate("bsmith"); assertEquals("RSA", certificate.getPublicKey().getAlgorithm()); assertEquals(1024, ((RSAKey) certificate.getPublicKey()).getModulus().bitLength()); Date notBefore = certificate.getNotBefore(); Date notAfter = certificate.getNotAfter(); assertEquals(365, (notAfter.getTime() - notBefore.getTime()) / (1000 * 60 * 60 * 24)); assertEquals("SHA256withRSA", certificate.getSigAlgName()); assertEquals(new X500Principal("CN=bob smith, OU=jboss, O=red hat, L=raleigh, ST=north carolina, C=us"), certificate.getSubjectX500Principal()); assertEquals(new X500Principal("CN=bob smith, OU=jboss, O=red hat, L=raleigh, ST=north carolina, C=us"), certificate.getIssuerX500Principal()); try { certificate.verify(certificate.getPublicKey()); } catch (Exception e) { fail("Exception not expected"); } assertEquals(1, certificate.getCriticalExtensionOIDs().size()); assertEquals(3, certificate.getNonCriticalExtensionOIDs().size()); assertEquals(Arrays.asList(X500.OID_KP_CLIENT_AUTH), certificate.getExtendedKeyUsage()); boolean[] keyUsage = certificate.getKeyUsage(); assertTrue(KeyUsage.digitalSignature.in(keyUsage)); final Collection<List<?>> names = certificate.getSubjectAlternativeNames(); assertEquals(2, names.size()); final Iterator<List<?>> iterator = names.iterator(); List<?> item = iterator.next(); assertEquals(2, item.size()); assertEquals(Integer.valueOf(GeneralName.RFC_822_NAME), item.get(0)); assertEquals("[email protected]", item.get(1)); item = iterator.next(); assertEquals(2, item.size()); assertEquals(Integer.valueOf(GeneralName.DNS_NAME), item.get(0)); assertEquals("bobsmith.example.com", item.get(1)); assertNotNull(certificate.getExtensionValue(X500.OID_CE_SUBJECT_KEY_IDENTIFIER)); assertNotNull(keyStore.getKey("bsmith", KEY_PASSWORD.toCharArray())); } finally { removeKeyStore(); } }
Example 18
Source File: Ca.java From strimzi-kafka-operator with Apache License 2.0 | 4 votes |
public boolean certNeedsRenewal(X509Certificate cert) { Date notAfter = cert.getNotAfter(); log.trace("Certificate {} expires on {}", cert.getSubjectDN(), notAfter); long msTillExpired = notAfter.getTime() - System.currentTimeMillis(); return msTillExpired < renewalDays * 24L * 60L * 60L * 1000L; }
Example 19
Source File: SecurityUtils.java From RISE-V2G with MIT License | 3 votes |
/** * Checks how many days a given certificate is still valid. * If the certificate is not valid any more, a negative number will be returned according to the number * of days the certificate is already expired. * * @param certificate The X509Certificiate to be checked for validity period * @return The number of days the given certificate is still valid, a negative number if already expired. */ public static short getValidityPeriod(X509Certificate certificate) { Date today = Calendar.getInstance().getTime(); Date certificateExpirationDate = certificate.getNotAfter(); long diff = certificateExpirationDate.getTime() - today.getTime(); return (short) TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS); }
Example 20
Source File: CertificadoService.java From Java_Certificado with MIT License | 3 votes |
private static Date dataValidade(Certificado certificado) throws CertificadoException { KeyStore keyStore = getKeyStore(certificado); if (keyStore == null) { throw new CertificadoException("Erro Ao pegar Keytore, verifique o Certificado"); } X509Certificate certificate = getCertificate(certificado, keyStore); return certificate.getNotAfter(); }