Example usage for java.security.cert X509Certificate checkValidity

List of usage examples for java.security.cert X509Certificate checkValidity

Introduction

In this page you can find the example usage for java.security.cert X509Certificate checkValidity.

Prototype

public abstract void checkValidity(Date date)
        throws CertificateExpiredException, CertificateNotYetValidException;

Source Link

Document

Checks that the given date is within the certificate's validity period.

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPair pair = generateRSAKeyPair();
    X509Certificate cert = generateV3Certificate(pair);
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());//from www .  ja v  a 2  s  . co m
}

From source file:io.vertx.config.vault.utils.Certificates.java

/**
 * See http://www.programcreek.com/java-api-examples/index.php?api=org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder
 *
 * @param keyPair The RSA keypair with which to generate the certificate
 * @param issuer  The issuer (and subject) to use for the certificate
 * @return An X509 certificate//from   www  .j  a v  a  2s .  co m
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
private static X509Certificate generateCert(final KeyPair keyPair, final String issuer)
        throws IOException, OperatorCreationException, CertificateException, NoSuchProviderException,
        NoSuchAlgorithmException, InvalidKeyException, SignatureException {
    final String subject = issuer;
    final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(new X500Name(issuer),
            BigInteger.ONE, new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)), new X500Name(subject),
            SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final GeneralNames subjectAltNames = new GeneralNames(new GeneralName(GeneralName.iPAddress, "127.0.0.1"));
    certificateBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectAlternativeName, false,
            subjectAltNames);

    final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
            .find("SHA1WithRSAEncryption");
    final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    final BcContentSignerBuilder signerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
    final AsymmetricKeyParameter keyp = PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    final ContentSigner signer = signerBuilder.build(keyp);
    final X509CertificateHolder x509CertificateHolder = certificateBuilder.build(signer);

    final X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(x509CertificateHolder);
    certificate.checkValidity(new Date());
    certificate.verify(keyPair.getPublic());
    return certificate;
}

From source file:Main.java

public static void checkValidityWithPublicKey(X509Certificate certificate, PublicKey publicKey)
        throws CertificateNotYetValidException, CertificateExpiredException {

    Date now = new Date();
    long nowTime = now.getTime();
    final int oneMinute = 60000;
    Date afterAddingOneMinute = new Date(nowTime + (5 * oneMinute));

    //we are checking the certificate against current time plus five minutes to prevent false failure because of sync problems
    certificate.checkValidity(afterAddingOneMinute);
    if (!certificate.getPublicKey().equals(publicKey)) {
        throw new RuntimeException("Failed to validate public key");
    }/*  w ww.  j a  va 2 s .  c  o m*/
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Creates a self signed certificate valid for 10 years (necessary to store
 * public keys in keystore)/*from   w ww .  j a  v  a2s  . c o m*/
 * 
 * @param privKey
 * @param pubKey
 * @param eMail
 * @param name
 * @return the certificate or NULL if there is an error
 */
private static X509Certificate createSelfSignedX509Certificate(PrivateKey privKey, PublicKey pubKey,
        String eMail, String name) {
    // Generate self-signed certificate
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.OU, "Panbox");
    builder.addRDN(BCStyle.O, "Panbox");
    builder.addRDN(BCStyle.CN, "localhost");

    if (eMail != null) {
        builder.addRDN(BCStyle.EmailAddress, eMail);
    }

    if (name != null) {
        builder.addRDN(BCStyle.NAME, name);
    }

    Calendar cal = Calendar.getInstance();
    Date notBefore = cal.getTime();

    cal.add(Calendar.YEAR, PanboxConstants.CERTIFICATE_LIFETIME_YEARS);
    Date notAfter = cal.getTime();

    BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore,
            notAfter, builder.build(), pubKey);

    X509Certificate cert = null;
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .setProvider(KeyConstants.PROV_BC).build(privKey);

        cert = new JcaX509CertificateConverter().setProvider(KeyConstants.PROV_BC)
                .getCertificate(certGen.build(sigGen));

        cert.checkValidity(new Date());

        cert.verify(cert.getPublicKey());

    } catch (NoSuchAlgorithmException | InvalidKeyException | OperatorCreationException | CertificateException
            | NoSuchProviderException | SignatureException e) {
        logger.warn("Exception caught in CryptCore.createSelfSignedX509Certificate, returning null", e);
    }

    return cert;
}

From source file:com.thoughtworks.go.security.X509CertificateGeneratorTest.java

@Test
public void shouldCreateCertWithDnThatIsValidFromEpochToNowPlusTenYears() throws Exception {
    X509CertificateGenerator generator = new X509CertificateGenerator();
    Registration certChain = generator.createCertificateWithDn("CN=hostname");
    Date epoch = new Date(0);
    X509Certificate cert = certChain.getFirstCertificate();
    cert.checkValidity(epoch); // does not throw CertificateNotYetValidException
    cert.checkValidity(DateUtils.addYears(new Date(), 9)); // does not throw CertificateNotYetValidException
}

From source file:com.thoughtworks.go.security.X509CertificateGeneratorTest.java

@Test
public void shouldCreateCertsThatIsValidFromEpochToNowPlusTenYears() throws Exception {
    X509CertificateGenerator generator = new X509CertificateGenerator();
    Registration caCert = generator.createAndStoreCACertificates(keystore);
    Date epoch = new Date(0);
    X509Certificate serverCert = caCert.getFirstCertificate();
    serverCert.checkValidity(epoch); // does not throw CertificateNotYetValidException
    serverCert.checkValidity(DateUtils.addYears(new Date(), 9)); // does not throw CertificateNotYetValidException
}

From source file:com.thoughtworks.go.security.X509CertificateGeneratorTest.java

@Test
public void shouldCreateCertsForAgentThatIsValidFromEpochToNowPlusTenYears() throws Exception {
    X509CertificateGenerator generator = new X509CertificateGenerator();
    Registration agentCertChain = generator.createAgentCertificate(keystore, "agentHostName");
    Date epoch = new Date(0);
    X509Certificate agentCert = agentCertChain.getFirstCertificate();
    agentCert.checkValidity(epoch); // does not throw CertificateNotYetValidException
    agentCert.checkValidity(DateUtils.addYears(new Date(), 9)); // does not throw CertificateNotYetValidException
}

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * Verifica si una firma XML embedida es válida según define
 * el est&aacute;ndar XML Signature (<a
 * href="http://www.w3.org/TR/xmldsig-core/#sec-CoreValidation">Core
 * Validation</a>), y si el certificado era v&aacute;lido en la fecha dada.
 * <p>//  w ww.  j a va 2s  .  c o m
 * 
 * Esta rutina <b>NO</b> verifica si el certificado embedido en
 * &lt;KeyInfo&gt; es v&aacute;lido (eso debe verificarlo con la autoridad
 * certificadora que emiti&oacute; el certificado), pero si verifica que la
 * llave utilizada para verificar corresponde a la contenida en el
 * certificado.
 * 
 * @param xml
 *            el nodo &lt;Signature&gt;
 * @param date
 *            una fecha en la que se verifica la validez del certificado
 * @return el resultado de la verificaci&oacute;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:com.zotoh.crypto.CryptoUte.java

/**
 * @param x/*ww w .j a  v  a 2  s  .co m*/
 * @return
 */
public static boolean tstCertValid(X509Certificate x) {

    tstObjArg("cert", x);

    boolean ok = false;
    try {
        x.checkValidity(new Date());
        ok = true;
    } catch (Exception e) {
    }

    return ok;
}

From source file:nl.clockwork.mule.ebms.cxf.EbMSSecSignatureInInterceptor.java

private boolean validateCertificate(KeyStore keyStore, X509Certificate certificate, Date date)
        throws KeyStoreException {
    try {// w  w w  .  j av a  2  s  .  co m
        certificate.checkValidity(date);
    } catch (Exception e) {
        return false;
    }
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        try {
            Certificate c = keyStore.getCertificate(aliases.nextElement());
            certificate.verify(c.getPublicKey());
            return true;
        } catch (KeyStoreException e) {
            throw e;
        } catch (Exception e) {
            logger.debug("", e);
        }
    }
    return false;
}