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

The following examples show how to use java.security.cert.X509Certificate#checkValidity() . 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: X509CA.java    From neoscada with Eclipse Public License 1.0 7 votes vote down vote up
public boolean isValid ()
{
    for ( final X509Certificate cert : this.certificates )
    {
        try
        {
            cert.checkValidity ();
            return true;
        }
        catch ( final Exception e )
        {
        }

    }
    return false;
}
 
Example 2
Source File: SSLKeyPairCerts.java    From vertx-tcp-eventbus-bridge with Apache License 2.0 6 votes vote down vote up
private X509Certificate generateSelfSignedCert(String certSub, KeyPair keyPair) throws Exception {
  final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
    new org.bouncycastle.asn1.x500.X500Name(certSub),
    BigInteger.ONE,
    new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
    new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)),
    new X500Name(certSub),
    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;
}
 
Example 3
Source File: CFDv3Debugger.java    From factura-electronica with Apache License 2.0 6 votes vote down vote up
private void dumpDigests() throws Exception {
    System.err.println(cfd.getCadenaOriginal());
    String certStr = cfd.document.getCertificado();
    Base64 b64 = new Base64();
    byte[] cbs = b64.decode(certStr);
    X509Certificate cert = (X509Certificate) KeyLoaderFactory.createInstance(
            KeyLoaderEnumeration.PUBLIC_KEY_LOADER,
            new ByteArrayInputStream(cbs)).getKey();
    cert.checkValidity();
    String sigStr = cfd.document.getSello();
    byte[] signature = b64.decode(sigStr);
    CFDv3.dump("Digestion firmada", signature, System.err);
    Cipher dec = Cipher.getInstance("RSA");
    dec.init(Cipher.DECRYPT_MODE, cert);
    byte[] result = dec.doFinal(signature);
    CFDv3.dump("Digestion decriptada", result, System.err);
    ASN1InputStream aIn = new ASN1InputStream(result);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
    CFDv3.dump("Sello", sigHash.getOctets(), System.err);
}
 
Example 4
Source File: JCEUtils.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static boolean verifySignedCertificate(X509Certificate issuerCertificate, X509Certificate signedCertificate) {
    try {
        issuerCertificate.checkValidity();
        signedCertificate.checkValidity();
        signedCertificate.verify(issuerCertificate.getPublicKey());
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 5
Source File: AuthSSLProtocolSocketFactoryForJsse10x.java    From iaf with Apache License 2.0 5 votes vote down vote up
public boolean isServerTrusted(X509Certificate[] certs) {
	if (certs != null) {
		for (int i = 0; i < certs.length; i++) {
			X509Certificate certificate = certs[i];
			try {
				certificate.checkValidity();
			}
			catch(Exception e) {
				log.debug("Exception checking certificate validity, assuming server not trusted",e);
				return false;
			}
		}
	}
	return true;
}
 
Example 6
Source File: LDAPLoginModule.java    From olat with Apache License 2.0 5 votes vote down vote up
private static boolean isCertificateValid(final X509Certificate x509Cert, final int daysFromNow) {
    try {
        x509Cert.checkValidity();
        if (daysFromNow > 0) {
            final Date nowPlusDays = new Date(System.currentTimeMillis() + (new Long(daysFromNow).longValue() * 24l * 60l * 60l * 1000l));
            x509Cert.checkValidity(nowPlusDays);
        }
    } catch (final Exception e) {
        return false;
    }
    return true;
}
 
Example 7
Source File: JarLoader.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the security certificates (signers) for the class data.
 */
private Certificate[] getSigners(String className, JarEntry je) throws IOException {

    try {
        Certificate[] list = je.getCertificates();
        if ((list == null) || (list.length == 0)) {
            return null;
        }

        for (int i = 0; i < list.length; i++) {
            if (!(list[i] instanceof X509Certificate)) {
                String msg = MessageService.getTextMessage(
                        MessageId.CM_UNKNOWN_CERTIFICATE, className,
                        getJarName());

                throw new SecurityException(msg);
            }

            X509Certificate cert = (X509Certificate) list[i];

            cert.checkValidity();
        }

        return list;

    } catch (GeneralSecurityException gse) {
        // convert this into an unchecked security
        // exception. Unchecked as eventually it has
        // to pass through a method that's only throwing
        // ClassNotFoundException
        throw handleException(gse, className);
    }
    
}
 
Example 8
Source File: JarSignatureVerifier.java    From multiapps-controller with Apache License 2.0 5 votes vote down vote up
private void checkValidityOfCertificate(X509Certificate x509Certificate) {
    try {
        x509Certificate.checkValidity();
    } catch (CertificateExpiredException | CertificateNotYetValidException e) {
        throw new SLException(e, e.getMessage());
    }
}
 
Example 9
Source File: PeriodValidator.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void validate(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);
    }
}
 
Example 10
Source File: ProviderApiManagerBase.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
protected Bundle loadCertificate(Provider provider, String certString) {
    Bundle result = new Bundle();
    if (certString == null) {
        setErrorResult(result, vpn_certificate_is_invalid, null);
        return result;
    }

    try {
        // API returns concatenated cert & key.  Split them for OpenVPN options
        String certificateString = null, keyString = null;
        String[] certAndKey = certString.split("(?<=-\n)");
        for (int i = 0; i < certAndKey.length - 1; i++) {
            if (certAndKey[i].contains("KEY")) {
                keyString = certAndKey[i++] + certAndKey[i];
            } else if (certAndKey[i].contains("CERTIFICATE")) {
                certificateString = certAndKey[i++] + certAndKey[i];
            }
        }

        RSAPrivateKey key = parseRsaKeyFromString(keyString);
        keyString = Base64.encodeToString(key.getEncoded(), Base64.DEFAULT);
        provider.setPrivateKey( "-----BEGIN RSA PRIVATE KEY-----\n" + keyString + "-----END RSA PRIVATE KEY-----");

        X509Certificate certificate = ConfigHelper.parseX509CertificateFromString(certificateString);
        certificate.checkValidity();
        certificateString = Base64.encodeToString(certificate.getEncoded(), Base64.DEFAULT);
        provider.setVpnCertificate( "-----BEGIN CERTIFICATE-----\n" + certificateString + "-----END CERTIFICATE-----");
        result.putBoolean(BROADCAST_RESULT_KEY, true);
    } catch (CertificateException | NullPointerException e) {
        e.printStackTrace();
        setErrorResult(result, vpn_certificate_is_invalid, null);
    }
    return result;
}
 
Example 11
Source File: SHelper.java    From Xndroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] certs, String arg1) throws CertificateException {
    Date today = new Date();
    for (X509Certificate certificate : certs) {
        certificate.checkValidity(today);
    }
}
 
Example 12
Source File: DeploymentBuilder.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected static PublicKey getPublicKeyFromPem(Key key) {
    PublicKey publicKey;
    if (key.getPublicKeyPem() != null) {
        publicKey = PemUtils.decodePublicKey(key.getPublicKeyPem().trim());
    } else {
        X509Certificate cert = PemUtils.decodeCertificate(key.getCertificatePem().trim());
        try {
            cert.checkValidity();
        } catch (CertificateException ex) {
            throw new RuntimeException(ex);
        }
        publicKey = cert.getPublicKey();
    }
    return publicKey;
}
 
Example 13
Source File: SSLSocketChannel.java    From nifi with Apache License 2.0 5 votes vote down vote up
public String getDn() throws CertificateException, SSLPeerUnverifiedException {
    final Certificate[] certs = engine.getSession().getPeerCertificates();
    if (certs == null || certs.length == 0) {
        throw new SSLPeerUnverifiedException("No certificates found");
    }

    final X509Certificate cert = CertificateUtils.convertAbstractX509Certificate(certs[0]);
    cert.checkValidity();
    return cert.getSubjectDN().getName().trim();
}
 
Example 14
Source File: X509Utils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Check that {@code cert} is signed by the {@code ca} and not revoked.
 *
 * <p>Support for certificate chains has not been implemented.
 *
 * @throws GeneralSecurityException for unsupported protocols, certs not signed by the TMCH,
 *         parsing errors, encoding errors, if the CRL is expired, or if the CRL is older than the
 *         one currently in memory.
 */
public static void verifyCertificate(
    X509Certificate rootCert, X509CRL crl, @Tainted X509Certificate cert, Date now)
        throws GeneralSecurityException {
  cert.checkValidity(checkNotNull(now, "now"));
  cert.verify(rootCert.getPublicKey());
  if (crl.isRevoked(cert)) {
    X509CRLEntry entry = crl.getRevokedCertificate(cert);
    throw new CertificateRevokedException(
        checkNotNull(entry.getRevocationDate(), "revocationDate"),
        Optional.ofNullable(entry.getRevocationReason()).orElse(CRLReason.UNSPECIFIED),
        firstNonNull(entry.getCertificateIssuer(), crl.getIssuerX500Principal()),
        ImmutableMap.of());
  }
}
 
Example 15
Source File: EasyX509TrustManager.java    From flex-blazeds with Apache License 2.0 5 votes vote down vote up
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException
{
    if (trustStore)
    {
        return;
    }
    if (certificates != null)
    {
        if (Trace.ssl)
        {
            Trace.trace("Server certificate chain:");
            for (int i = 0; i < certificates.length; i++)
            {
                Trace.trace("X509Certificate[" + i + "]=" + certificates[i]);
            }
        }
    }
    if ((certificates != null) && (certificates.length == 1))
    {
        X509Certificate certificate = certificates[0];
        try
        {
            certificate.checkValidity();
        }
        catch (CertificateException e)
        {
            if (Trace.ssl)
            {
                Trace.trace(e.toString());
            }
            throw e;
        }
    }
    else
    {
        standardTrustManager.checkServerTrusted(certificates, authType);
    }
}
 
Example 16
Source File: CertificatesVerifier.java    From wechatpay-apache-httpclient with Apache License 2.0 5 votes vote down vote up
@Override
public X509Certificate getValidCertificate() {
  for (X509Certificate x509Cert : certificates.values()) {
    try {
      x509Cert.checkValidity();

      return x509Cert;
    } catch (CertificateExpiredException | CertificateNotYetValidException e) {
      continue;
    }
  }

  throw new NoSuchElementException("没有有效的微信支付平台证书");
}
 
Example 17
Source File: SkillRequestSignatureVerifier.java    From micronaut-aws with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies the certificate authenticity using the configured TrustStore and the signature of
 * the skill request. This method will throw a {@link SecurityException} if the signature
 * does not pass verification.
 *
 * {@inheritDoc}
 */
public void verify(final AlexaHttpRequest alexaHttpRequest) {
    String baseEncoded64Signature = alexaHttpRequest.getBaseEncoded64Signature();
    String signingCertificateChainUrl = alexaHttpRequest.getSigningCertificateChainUrl();
    if ((baseEncoded64Signature == null) || (signingCertificateChainUrl == null)) {
        throw new SecurityException(
                "Missing signature/certificate for the provided skill request");
    }

    try {
        X509Certificate signingCertificate = getCertificateFromCache(signingCertificateChainUrl);
        if (signingCertificate != null && signingCertificate.getNotAfter().after(new Date())) {
            /*
             * check the before/after dates on the certificate are still valid for the present
             * time
             */
            signingCertificate.checkValidity();
        } else {
            signingCertificate = retrieveAndVerifyCertificateChain(signingCertificateChainUrl);

            // if certificate is valid, then add it to the cache
            CERTIFICATE_CACHE.put(signingCertificateChainUrl, signingCertificate);
        }

        // verify that the request was signed by the provided certificate
        Signature signature = Signature.getInstance(AskHttpServerConstants.SIGNATURE_ALGORITHM);
        signature.initVerify(signingCertificate.getPublicKey());
        signature.update(alexaHttpRequest.getSerializedRequestEnvelope());

        if (!signature.verify(Base64.getDecoder().decode(baseEncoded64Signature
                .getBytes(AskHttpServerConstants.CHARACTER_ENCODING)))) {
            throw new SecurityException(
                    "Failed to verify the signature/certificate for the provided skill request");
        }
    } catch (GeneralSecurityException | IOException ex) {
        throw new SecurityException(
                "Failed to verify the signature/certificate for the provided skill request",
                ex);
    }
}
 
Example 18
Source File: CFDv3.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
@Override
public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
    String nc = new String(cert.getSerialNumber().toByteArray());
    if (!nc.equals("20001000000200001428")) {
        cert.checkValidity();
    }
    String signature = getSignature(key);
    document.setSello(signature);
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
    document.setNoCertificado(nc);
}
 
Example 19
Source File: CertificateTool.java    From peer-os with Apache License 2.0 4 votes vote down vote up
/**
 * *********************************************************************************** Generate x509 Certificate
 *
 * @param keyPair KeyPair
 * @param certificateData CertificateData
 *
 * @return X509Certificate
 */
public X509Certificate generateSelfSignedCertificate( KeyPair keyPair, CertificateData certificateData )
{
    try
    {
        Security.addProvider( new org.bouncycastle.jce.provider.BouncyCastleProvider() );

        setDateParamaters();

        //******************************************************************************
        // Generate self-signed certificate

        X500NameBuilder builder = new X500NameBuilder( BCStyle.INSTANCE );
        builder.addRDN( BCStyle.CN, certificateData.getCommonName() );
        builder.addRDN( BCStyle.OU, certificateData.getOrganizationUnit() );
        builder.addRDN( BCStyle.O, certificateData.getOrganizationName() );
        builder.addRDN( BCStyle.C, certificateData.getCountry() );
        builder.addRDN( BCStyle.L, certificateData.getLocalityName() );
        builder.addRDN( BCStyle.ST, certificateData.getState() );
        builder.addRDN( BCStyle.EmailAddress, certificateData.getEmail() );

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

        X509v3CertificateBuilder certGen =
                new JcaX509v3CertificateBuilder( builder.build(), serial, notBefore, notAfter, builder.build(),
                        keyPair.getPublic() );
        ContentSigner sigGen = new JcaContentSignerBuilder( "SHA256WithRSAEncryption" ).
                                                                                               build( keyPair
                                                                                                       .getPrivate() );
        X509Certificate x509cert = new JcaX509CertificateConverter().
                                                                            getCertificate(
                                                                                    certGen.build( sigGen ) );
        x509cert.checkValidity( new Date() );
        x509cert.verify( x509cert.getPublicKey() );
        return x509cert;
    }
    catch ( Exception t )
    {
        throw new ActionFailedException( "Failed to generate self-signed certificate!", t );
    }
}
 
Example 20
Source File: FTPSTrustManager.java    From Aria with Apache License 2.0 4 votes vote down vote up
@Override public void checkServerTrusted(X509Certificate[] certificates, String authType)
    throws CertificateException {
  for (X509Certificate certificate : certificates) {
    certificate.checkValidity();
  }
}