Example usage for java.security.cert X509Certificate verify

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

Introduction

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

Prototype

public abstract void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchProviderException, SignatureException;

Source Link

Document

Verifies that this certificate was signed using the private key that corresponds to the specified public key.

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 source file:Main.java

protected static void verifyX509Certificate(X509Certificate cert, PublicKey publicKey, String sigProvider)
        throws GeneralSecurityException {
    if (sigProvider == null) {
        cert.verify(publicKey);
    } else {/*from w  w  w .ja v a 2 s  . c o m*/
        cert.verify(publicKey, sigProvider);
    }
}

From source file:Main.java

/**
 * Checks whether given X.509 certificate is self-signed.
 *///from  w  w w  .j  a v a2s .co  m
public static boolean isSelfSigned(X509Certificate cert)
        throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException {
    try {
        // Try to verify certificate signature with its own public key
        PublicKey key = cert.getPublicKey();
        cert.verify(key);
        return true;
    } catch (SignatureException sigEx) {
        // Invalid signature --> not self-signed
        return false;
    } catch (InvalidKeyException keyEx) {
        // Invalid key --> not self-signed
        return false;
    }
}

From source file:Main.java

public static boolean isTrustAnchor(X509Certificate certificate) throws IOException {
    boolean trust_anchor = certificate.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())
            && certificate.getBasicConstraints() >= 0;
    if (trust_anchor) {
        try {/* w ww.  j  a  v a2 s .  c  o m*/
            certificate.verify(certificate.getPublicKey());
        } catch (Exception e) {
            throw new IOException(e);
        }
        return true;
    }
    return false;
}

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   ww  w .j a  v a2  s. 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:com.eucalyptus.auth.euare.EuareServerCertificateUtil.java

public static boolean verifyCertificate(final String certPem, final boolean checkSigner) {
    try {//from w w  w . j ava2s.  c  o  m
        final X509Certificate cert = PEMFiles.getCert(B64.standard.dec(certPem));
        cert.checkValidity();
        if (checkSigner) {
            final Credentials euareCred = SystemCredentials.lookup(Euare.class);
            final X509Certificate signer = euareCred.getCertificate();
            cert.verify(signer.getPublicKey());
        }
        return true;
    } catch (final Exception ex) {
        return false;
    }
}

From source file:be.fedict.trust.TrustValidator.java

/**
 * Gives back the trust linker result of a verification of a self-signed
 * X509 certificate./*w w w . ja  v a 2  s .com*/
 * 
 * @param certificate
 *            the self-signed certificate to validate.
 * @return the validation result.
 */
public static TrustLinkerResult getSelfSignedResult(X509Certificate certificate) {

    if (false == certificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) {
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST,
                "root certificate should be self-signed: " + certificate.getSubjectX500Principal());
    }
    try {
        certificate.verify(certificate.getPublicKey());
    } catch (Exception e) {
        return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE,
                "certificate signature error: " + e.getMessage());
    }
    return new TrustLinkerResult(true);
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * Verify that one X.509 certificate was signed using the private key that
 * corresponds to the public key of a second certificate.
 *
 * @return True if the first certificate was signed by private key
 *         corresponding to the second signature
 * @param signedCert/*  w w  w. j a  v  a2s . c o  m*/
 *            The signed certificate
 * @param signingCert
 *            The signing certificate
 * @throws CryptoException
 *             If there was a problem verifying the signature.
 */
public static boolean verifyCertificate(X509Certificate signedCert, X509Certificate signingCert)
        throws CryptoException {
    try {
        signedCert.verify(signingCert.getPublicKey());
        return true;
    }
    // Verification failed
    catch (InvalidKeyException ex) {
        return false;
    } catch (SignatureException ex) {
        return false;
    }
    // Problem verifying
    catch (NoSuchProviderException ex) {
        throw new CryptoException(res.getString("NoVerifyCertificate.exception.message"), ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new CryptoException(res.getString("NoVerifyCertificate.exception.message"), ex);
    } catch (CertificateException ex) {
        throw new CryptoException(res.getString("NoVerifyCertificate.exception.message"), ex);
    }
}

From source file:be.e_contract.mycarenet.etee.EncryptionToken.java

/**
 * RFC 3820/* w w w.  j a  va 2 s.co  m*/
 * 
 * @param certificate
 * @param issuer
 */
private void verifyProxyCertificate(X509Certificate certificate, X509Certificate issuer) {
    try {
        certificate.verify(issuer.getPublicKey());
        issuer.checkValidity();
    } catch (Exception e) {
        throw new SecurityException("not a proxy certificate");
    }
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 * @param cert/*from w  ww . j a v  a2s .co m*/
 * @return true when the certificate is self signed
 */
public static boolean isCertificateSelfSigned(X509Certificate cert) {
    try {
        PublicKey publicKey = cert.getPublicKey();
        cert.verify(publicKey);
        return true;
    } catch (java.security.SignatureException sigEx) {
        LOG.info("ERROR : SignatureException {}", sigEx.getMessage());
        LOG.debug("ERROR : SignatureException {}", sigEx);
        return false;
    } catch (InvalidKeyException keyEx) {
        // Invalid key --> not self-signed
        LOG.info("ERROR : InvalidKeyException {}", keyEx.getMessage());
        LOG.debug("ERROR : InvalidKeyException {}", keyEx);
        return false;
    } catch (CertificateException certExc) {
        LOG.info("ERROR : CertificateException {}", certExc.getMessage());
        LOG.debug("ERROR : CertificateException {}", certExc);
        return false;
    } catch (NoSuchAlgorithmException nsaExc) {
        LOG.info("ERROR : Bad algorithm: " + nsaExc.getMessage());
        LOG.debug("ERROR : Bad algorithm: " + nsaExc);
        return false;
    } catch (NoSuchProviderException nspExc) {
        LOG.info("ERROR : Bad provider: " + nspExc.getMessage());
        LOG.debug("ERROR : Bad provider: " + nspExc);
        return false;
    }
}