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 void verify(PublicKey key, Provider sigProvider)
        throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, 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:net.ripe.rpki.commons.crypto.x509cert.X509CertificateUtil.java

public static void verify(X509Certificate certificate, PublicKey publicKey)
        throws InvalidKeyException, SignatureException {
    try {//from   w  w w  .java  2  s  .  c om
        certificate.verify(publicKey, DEFAULT_SIGNATURE_PROVIDER);
    } catch (CertificateException e) {
        throw new IllegalArgumentException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException(e);
    } catch (NoSuchProviderException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

/**
 * @param kp/*from w  w  w  . java  2s. c  om*/
 * @param issuer
 * @param subject
 *
 * @return
 */
public static X509Certificate generateCaCertificate(final String friendlyName, final KeyPair kp,
        final BigInteger serial, final X509Name issuer, final X509Name subject) throws Exception {

    X509Certificate cert = null;

    X509V3CertificateGenerator gen = new X509V3CertificateGenerator();
    gen.setIssuerDN(issuer);
    setNotBeforeNotAfter(gen, 20); // The CA certificate is valid for 20 years
    gen.setSubjectDN(subject);
    gen.setPublicKey(kp.getPublic());
    gen.setSignatureAlgorithm(getSignatureAlgorithm());

    if (serial != null)
        gen.setSerialNumber(serial);
    else
        gen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));

    gen = addCaExtensions(gen, kp.getPublic());
    // gen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
    // new SubjectKeyIdentifierStructure(kp.getPublic()));
    cert = gen.generate(kp.getPrivate(), "BC");

    cert.checkValidity();
    cert.verify(kp.getPublic(), "BC");

    if (friendlyName != null) {
        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) cert;
        bagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(friendlyName));
    }

    return cert;
}

From source file:mitm.common.security.crl.PKIXRevocationChecker.java

private void verifyCertificate(X509Certificate certificate, PublicKey issuerPublicKey) throws CRLException {
    try {/* ww  w.  j a  va2s.  c o m*/
        certificate.verify(issuerPublicKey, securityFactory.getNonSensitiveProvider());
    } catch (InvalidKeyException e) {
        throw new CRLException("Certificate verification failed.", e);
    } catch (CertificateException e) {
        throw new CRLException("Certificate verification failed.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CRLException("Certificate verification failed.", e);
    } catch (NoSuchProviderException e) {
        throw new CRLException("Certificate verification failed.", e);
    } catch (SignatureException e) {
        throw new CRLException("Certificate verification failed.", e);
    }
}

From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java

/**
 *  ?     ? ?  ?? ?_1 // ww  w . ja v a2s  .  c  om
 * ?    ? ?
 *
 * @param signers
 * @param clientCerts
 * @return
 * @throws CertStoreException
 */
private boolean checkNucOneCertificateType(SignerInformationStore signers, CertStore clientCerts)
        throws CertStoreException {

    Iterator it = signers.getSigners().iterator();
    boolean result = false;
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertSelector signerConstraints = signer.getSID();
        Collection certCollection = clientCerts.getCertificates(signerConstraints);
        Iterator certIt = certCollection.iterator();
        if (certCollection.size() == 0) {
            throw new RuntimeException(
                    "    ?  ? .");
        }
        while (certIt.hasNext()) {
            X509Certificate userCert = (X509Certificate) certIt.next();
            X509Certificate certForCheck = null;
            boolean isMyVersion = false;
            try {
                if (TypeOfRespondent.FIRM.equals(typeOfRespondent)) {
                    X509Certificate certNuc1Gost = (X509Certificate) createCerificate_nuc1_gost();
                    userCert.verify(certNuc1Gost.getPublicKey(), providerName);
                    certForCheck = certNuc1Gost;
                } else {
                    X509Certificate certNuc1Rsa = (X509Certificate) createCerificate_nuc1_rsa();
                    userCert.verify(certNuc1Rsa.getPublicKey(), providerName);
                    certForCheck = certNuc1Rsa;
                }

                isMyVersion = true;
            } catch (Exception ex) {
                //  ? ? ?  ? 1
                result = false;
            }
            if (isMyVersion) { // ?   ? ?  ?? ?_1  
                try {
                    certForCheck.checkValidity(); // ? ? ?
                } catch (CertificateExpiredException ex) {
                    throw new RuntimeException(
                            " ? ? ? 1.0,   ? ? 1.0  ? ??");
                } catch (CertificateNotYetValidException ex) {
                    throw new RuntimeException(
                            " ? ? ? 1.0,   ? ? 1.0   ?.");
                }
                try {
                    if (isNotRevokedCertNucOne(userCert)) { // ? ? ?
                        return true;
                    } else {
                        throw new RuntimeException(
                                "C ?   .");
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex.getMessage());
                }
            }
        }
    }
    return result;
}

From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java

/**
 *  ?     ? ?  ?? ?_2 /*from  w w  w .ja  v a2 s . c om*/
 * ?    ? ?
 *
 * @param signers
 * @param clientCerts
 * @return
 * @throws CertStoreException
 */
private boolean checkNucTwoCertificateType(SignerInformationStore signers, CertStore clientCerts)
        throws CertStoreException {
    Iterator it = signers.getSigners().iterator();
    boolean result = false;
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertSelector signerConstraints = signer.getSID();
        Collection certCollection = clientCerts.getCertificates(signerConstraints);
        Iterator certIt = certCollection.iterator();
        //System.out.println(  );
        if (certCollection.size() == 0) {
            throw new RuntimeException(
                    "    ?  ? .");
        }
        while (certIt.hasNext()) {
            X509Certificate userCert = (X509Certificate) certIt.next();
            boolean isMyVersion = false;
            X509Certificate certForCheck = null;
            try {
                if (TypeOfRespondent.FIRM.equals(typeOfRespondent)) {
                    X509Certificate certNuc2Gost = (X509Certificate) createCerificate_nuc2_gost();
                    X509Certificate certKucGost = (X509Certificate) createCerificate_kuc_gost();
                    userCert.verify(certNuc2Gost.getPublicKey(), providerName);
                    certNuc2Gost.verify(certKucGost.getPublicKey(), providerName);
                    certForCheck = certNuc2Gost;
                } else {
                    X509Certificate certNuc2Rsa = (X509Certificate) createCerificate_nuc2_rsa();
                    X509Certificate certKucRsa = (X509Certificate) createCerificate_kuc_rsa();
                    userCert.verify(certNuc2Rsa.getPublicKey(), providerName);
                    certNuc2Rsa.verify(certKucRsa.getPublicKey(), providerName);
                    certForCheck = certNuc2Rsa;
                }

                isMyVersion = true;
            } catch (Exception ex) {
                result = false;

            }
            if (isMyVersion) { // ?   ? ?  ?? ?_1  
                try {
                    certForCheck.checkValidity();
                } catch (CertificateExpiredException ex) {
                    throw new RuntimeException(
                            " ? ? ? 2.0,   ? ? 2.0  ? ??");
                } catch (CertificateNotYetValidException ex) {
                    throw new RuntimeException(
                            " ? ? ? 2.0,   ? ? 2.0   ?.");
                }

                try {
                    if (isNotRevokedCertNucTwo(userCert)) {
                        result = true;
                        return true;
                    } else {
                        throw new RuntimeException(
                                "C ?   .");
                    }
                } catch (Exception ex) {
                    throw new RuntimeException(ex.getMessage());
                }
            }

        }
    }
    return result;
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.MockX509SecurityHandler.java

@Override
public X509SecurityManagerMaterial generateMaterial(X509MaterialParameter materialParameter) throws Exception {
    ApplicationId appId = materialParameter.getApplicationId();
    String appUser = materialParameter.getAppUser();
    Integer cryptoMaterialVersion = materialParameter.getCryptoMaterialVersion();

    KeyPair keyPair = generateKeyPair();
    PKCS10CertificationRequest csr = generateCSR(appId, appUser, keyPair, cryptoMaterialVersion);
    assertEquals(appUser, HopsUtil.extractCNFromSubject(csr.getSubject().toString()));
    assertEquals(appId.toString(), HopsUtil.extractOFromSubject(csr.getSubject().toString()));
    assertEquals(String.valueOf(cryptoMaterialVersion),
            HopsUtil.extractOUFromSubject(csr.getSubject().toString()));

    // Sign CSR/*w  w w .  ja  v a 2s.  c  om*/
    CertificateBundle certificateBundle = sendCSRAndGetSigned(csr);
    certificateBundle.getCertificate().checkValidity();
    long expiration = certificateBundle.getCertificate().getNotAfter().getTime();
    long epochNow = DateUtils.localDateTime2UnixEpoch(DateUtils.getNow());
    assertTrue(expiration >= epochNow);
    assertNotNull(certificateBundle.getIssuer());
    RMAppSecurityActions actor = getRmAppSecurityActions();
    if (actor instanceof TestingRMAppSecurityActions) {
        X509Certificate caCert = ((TestingRMAppSecurityActions) actor).getCaCert();
        certificateBundle.getCertificate().verify(caCert.getPublicKey(), "BC");
    }
    certificateBundle.getCertificate().verify(certificateBundle.getIssuer().getPublicKey(), "BC");

    KeyStoresWrapper appKeystores = createApplicationStores(certificateBundle, keyPair.getPrivate(), appUser,
            appId);
    X509Certificate extractedCert = (X509Certificate) appKeystores.getKeystore().getCertificate(appUser);
    byte[] rawKeystore = appKeystores.getRawKeyStore(TYPE.KEYSTORE);
    assertNotNull(rawKeystore);
    assertNotEquals(0, rawKeystore.length);

    File keystoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_kstore.jks").toFile();
    // Keystore should have been deleted
    assertFalse(keystoreFile.exists());
    char[] keyStorePassword = appKeystores.getKeyStorePassword();
    assertNotNull(keyStorePassword);
    assertNotEquals(0, keyStorePassword.length);

    byte[] rawTrustStore = appKeystores.getRawKeyStore(TYPE.TRUSTSTORE);
    File trustStoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_tstore.jks").toFile();
    // Truststore should have been deleted
    assertFalse(trustStoreFile.exists());
    char[] trustStorePassword = appKeystores.getTrustStorePassword();
    assertNotNull(trustStorePassword);
    assertNotEquals(0, trustStorePassword.length);

    verifyContentOfAppTrustStore(rawTrustStore, trustStorePassword, appUser, appId);

    if (actor instanceof TestingRMAppSecurityActions) {
        X509Certificate caCert = ((TestingRMAppSecurityActions) actor).getCaCert();
        extractedCert.verify(caCert.getPublicKey(), "BC");
    }
    assertEquals(appUser, HopsUtil.extractCNFromSubject(extractedCert.getSubjectX500Principal().getName()));
    assertEquals(appId.toString(),
            HopsUtil.extractOFromSubject(extractedCert.getSubjectX500Principal().getName()));
    assertEquals(String.valueOf(cryptoMaterialVersion),
            HopsUtil.extractOUFromSubject(extractedCert.getSubjectX500Principal().getName()));
    return new X509SecurityManagerMaterial(appId, rawKeystore, appKeystores.getKeyStorePassword(),
            rawTrustStore, appKeystores.getTrustStorePassword(), expiration);
}