Java Code Examples for java.security.cert.X509Certificate#getNotBefore()

The following examples show how to use java.security.cert.X509Certificate#getNotBefore() . 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 vote down vote up
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: TlsHelperTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: EntityCertificate.java    From FairEmail with GNU General Public License v3.0 6 votes vote down vote up
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 4
Source File: CertificatePriorityComparator.java    From cwac-netsecurity with Apache License 2.0 6 votes vote down vote up
@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: TlsHelperTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: TlsHelperTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 7
Source File: StartDateTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 8
Source File: StartDateTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 9
Source File: StartDateTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 10
Source File: StartDateTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 11
Source File: StartDateTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 12
Source File: StartDateTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate(String alias) throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate(alias);
    return cert.getNotBefore();
}
 
Example 13
Source File: StartDateTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 14
Source File: VpnCertificateValidator.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
private Calendar calculateOffsetCertificateValidity(X509Certificate certificate) {
    Calendar limitDate = calendarProvider.getCalendar();
    Date startDate = certificate.getNotBefore();
    // if certificates start date is before current date just return the current date without an offset
    if (startDate.getTime() >= limitDate.getTime().getTime()) {
        return limitDate;
    }
    // else add an offset of 15 days to the current date
    limitDate.add(Calendar.DAY_OF_YEAR, 15);

    return limitDate;
}
 
Example 15
Source File: StartDateTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 16
Source File: X509Cert.java    From xipki with Apache License 2.0 5 votes vote down vote up
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 17
Source File: CertificateMetas.java    From apk-parser with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 18
Source File: StartDateTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static Date getIssueDate() throws Exception {
    KeyStore ks = KeyStore.getInstance("jks");
    try (FileInputStream fis = new FileInputStream("jks")) {
        ks.load(fis, "changeit".toCharArray());
    }
    X509Certificate cert = (X509Certificate)ks.getCertificate("me");
    return cert.getNotBefore();
}
 
Example 19
Source File: DProperties.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private void populateCertificateNode(DefaultMutableTreeNode certificateNode, X509Certificate certificate)
		throws CryptoException {
	try {
		String version = MessageFormat.format(res.getString("DProperties.properties.Version"),
				"" + certificate.getVersion());
		certificateNode.add(new DefaultMutableTreeNode(version));

		String subject = MessageFormat.format(res.getString("DProperties.properties.Subject"),
				X500NameUtils.x500PrincipalToX500Name(certificate.getSubjectX500Principal()));
		certificateNode.add(new DefaultMutableTreeNode(subject));

		String issuer = MessageFormat.format(res.getString("DProperties.properties.Issuer"),
				X500NameUtils.x500PrincipalToX500Name(certificate.getIssuerX500Principal()));
		certificateNode.add(new DefaultMutableTreeNode(issuer));

		String serialNumber = MessageFormat.format(res.getString("DProperties.properties.SerialNumber"),
				new BigInteger(certificate.getSerialNumber().toByteArray()).toString(16).toUpperCase());
		certificateNode.add(new DefaultMutableTreeNode(serialNumber));

		Date validFromDate = certificate.getNotBefore();
		String validFrom = MessageFormat.format(res.getString("DProperties.properties.ValidFrom"),
				StringUtils.formatDate(validFromDate));
		certificateNode.add(new DefaultMutableTreeNode(validFrom));

		Date validUntilDate = certificate.getNotAfter();
		String validUntil = MessageFormat.format(res.getString("DProperties.properties.ValidUntil"),
				StringUtils.formatDate(validUntilDate));
		certificateNode.add(new DefaultMutableTreeNode(validUntil));

		createPublicKeyNodes(certificateNode, certificate);

		String signatureAlgorithm = MessageFormat.format(
				res.getString("DProperties.properties.SignatureAlgorithm"),
				X509CertUtil.getCertificateSignatureAlgorithm(certificate));
		certificateNode.add(new DefaultMutableTreeNode(signatureAlgorithm));

		byte[] cert = certificate.getEncoded();

		String md5 = MessageFormat.format(res.getString("DProperties.properties.Md5Fingerprint"),
				DigestUtil.getFriendlyMessageDigest(cert, DigestType.MD5));
		certificateNode.add(new DefaultMutableTreeNode(md5));

		String sha1 = MessageFormat.format(res.getString("DProperties.properties.Sha1Fingerprint"),
				DigestUtil.getFriendlyMessageDigest(cert, DigestType.SHA1));
		certificateNode.add(new DefaultMutableTreeNode(sha1));
	} catch (CertificateEncodingException ex) {
		throw new CryptoException(res.getString("DProperties.NoGetProperties.exception.message"), ex);
	}
}
 
Example 20
Source File: CertModel.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 解析证书
 *
 * @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;
}