Example usage for java.security.cert Certificate verify

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

Introduction

In this page you can find the example usage for java.security.cert Certificate 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:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 *
 * @param cert/*from   w  w  w  .java2  s  .  co m*/
 * @param pubKey
 * @return
 */
public boolean verifyCert(Certificate cert, PublicKey pubKey) {
    try {
        cert.verify(pubKey);
    } catch (Throwable t) {
        return false;
    }
    return true;
}

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

boolean verifySigned(File keystore, Certificate agentCertificate) {
    try {//from   w w w .j ava 2 s  .  c  o  m
        KeyStore store = KeyStore.getInstance("JKS");
        FileInputStream inputStream = new FileInputStream(keystore);
        store.load(inputStream, PASSWORD_AS_CHAR_ARRAY);
        IOUtils.closeQuietly(inputStream);
        KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store
                .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));
        Certificate intermediateCertificate = intermediateEntry.getCertificate();
        agentCertificate.verify(intermediateCertificate.getPublicKey());
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:org.cesecore.certificates.ca.X509CA.java

@Override
public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain)
        throws SignRequestSignatureException {
    // First verify that we signed this certificate
    try {/*from w w w .  j a  va  2  s .  c o m*/
        if (cert != null) {
            final PublicKey verifyKey;
            final X509Certificate cacert = (X509Certificate) getCACertificate();
            if (cacert != null) {
                verifyKey = cacert.getPublicKey();
            } else {

                verifyKey = cryptoToken
                        .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));

            }
            cert.verify(verifyKey);
        }
    } catch (CryptoTokenOfflineException e) {
        throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7",
                e);
    } catch (InvalidKeyException e) {
        throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e);
    } catch (CertificateException e) {
        throw new SignRequestSignatureException("An encoding error was encountered.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignRequestSignatureException(
                "The certificate provided was signed with an invalid algorithm.", e);
    } catch (NoSuchProviderException e) {
        throw new SignRequestSignatureException(
                "The crypto provider was not found for verification of the certificate.", e);
    } catch (SignatureException e) {
        throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?",
                e);
    }

    Collection<Certificate> chain = getCertificateChain();
    ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>();
    try {
        if (cert != null) {
            certList.add(new JcaX509CertificateHolder((X509Certificate) cert));
        }
        if (includeChain) {
            for (Certificate certificate : chain) {
                certList.add(new JcaX509CertificateHolder((X509Certificate) certificate));
            }
        }
    } catch (CertificateEncodingException e) {
        throw new SignRequestSignatureException("Could not encode certificate", e);
    }
    try {
        CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes());
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        final PrivateKey privateKey = cryptoToken
                .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        if (privateKey == null) {
            String msg1 = "createPKCS7: Private key does not exist!";
            log.debug(msg1);
            throw new SignRequestSignatureException(msg1);
        }
        String signatureAlgorithmName = AlgorithmTools
                .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm());
        try {
            ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(cryptoToken.getSignProviderName()).build(privateKey);
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate()));
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e);
        }
        gen.addCertificates(new CollectionStore(certList));
        CMSSignedData s = null;
        CAToken catoken = getCAToken();
        if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) {
            log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm "
                    + privateKey.getAlgorithm());
            s = gen.generate(msg, true);
        } else {
            String msg1 = "CA Token does not exist!";
            log.debug(msg);
            throw new SignRequestSignatureException(msg1);
        }
        return s.getEncoded();
    } catch (CryptoTokenOfflineException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        //FIXME: This right here is just nasty
        throw new RuntimeException(e);
    }
}

From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java

private boolean isIssuerCA(final Certificate cert, final Certificate cacert) {
    if (!StringUtils.equals(CertTools.getIssuerDN(cert), CertTools.getSubjectDN(cacert))) {
        return false;
    }// w w  w  .  j  a  v a2 s.  c  o  m
    try {
        cert.verify(cacert.getPublicKey());
        return true;
    } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException
            | SignatureException e) {
        return false;
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

/**
 * Check if subject certificate is signed by issuer certificate. Used in
 * /*from   w w  w . j  a  v a 2 s .  co m*/
 * @see #upgradeFromOldCAKeyStore(Admin, String, byte[], char[], char[], String). This method does a lazy check: if signature verification failed
 *      for any reason that prevent verification, e.g. signature algorithm not supported, method returns false. Author: Marco Ferrante
 * 
 * @param subject Subject certificate
 * @param issuer Issuer certificate
 * @return true if subject certificate is signed by issuer certificate
 * @throws java.lang.Exception
 */
private boolean verifyIssuer(Certificate subject, Certificate issuer) {
    try {
        PublicKey issuerKey = issuer.getPublicKey();
        subject.verify(issuerKey);
        return true;
    } catch (java.security.GeneralSecurityException e) {
        return false;
    }
}

From source file:org.ejbca.ui.cli.ca.CaImportCVCCACommand.java

public void execute(String[] args) throws ErrorAdminCommandException {
    if (args.length < 4) {
        getLogger().info("Description: " + getDescription());
        getLogger().info(/*w  w  w. ja  v a2s .  c  o m*/
                "Usage 1: " + getCommand() + " <CA name> <pkcs8 RSA private key file> <certificate file>");
        getLogger().info(" Imports a private key and a self signed CVCA certificate and creates a CVCA.");
        getLogger().info("Usage 2: " + getCommand()
                + " <CA name> <pkcs8 private key file> <certificate file> <DN of form C=country,CN=mnemonic,SERIALNUMBER=sequence> <signatureAlgorithm> <validity days>");
        getLogger().info(
                " Imports a private key and generates a new self signed CVCA certificate with the given DN and creates a CVCA.");
        getLogger().info(
                " Signature algorithm can be SHA1WithRSA, SHA256WithRSA, SHA1WithECDSA, SHA224WithECDSA, SHA256WithECDSA, etc.");
        getLogger().info(
                " SERIALNUMBER will not be a part of the CAs DN, it is only used to set a specified sequence (should be of form 00001). Can be left out, and a random sequence is then generated.");
        return;
    }
    try {
        String caName = args[1];
        String pkFile = args[2];
        String certFile = args[3];

        // Import key and certificate
        CryptoProviderTools.installBCProvider();
        byte[] pkbytes = FileTools.readFiletoBuffer(pkFile);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkbytes);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "BC"); // Doesn't matter if we say RSA here, it will fix an EC key as well
        PrivateKey privKey = keyfact.generatePrivate(spec);

        byte[] certbytes = FileTools.readFiletoBuffer(certFile);
        Certificate cert = null;
        try {
            // First check if it was a PEM formatted certificate
            Collection<Certificate> certs = CertTools.getCertsFromPEM(new ByteArrayInputStream(certbytes));
            cert = certs.iterator().next();
        } catch (IOException e) {
            // This was not a PEM certificate, I hope it's binary...
            cert = CertTools.getCertfromByteArray(certbytes);
        }
        PublicKey pubKey = cert.getPublicKey();
        // Verify that the public and private key belongs together
        getLogger().info("Testing keys with algorithm: " + pubKey.getAlgorithm());
        KeyTools.testKey(privKey, pubKey, null);

        Certificate cacert = null;
        if (args.length > 6) {
            // Create a self signed CVCA cert from the DN
            getLogger().info("Generating new self signed certificate.");
            String dn = args[4];
            String sigAlg = args[5];
            Integer valdays = Integer.parseInt(args[6]);

            String country = CertTools.getPartFromDN(dn, "C");
            String mnemonic = CertTools.getPartFromDN(dn, "CN");
            String seq = CertTools.getPartFromDN(dn, "SERIALNUMBER");
            if (StringUtils.isEmpty(seq)) {
                seq = RandomStringUtils.randomNumeric(5);
                getLogger().info("No sequence given, using random 5 number sequence: " + seq);
            }
            HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq);
            CAReferenceField caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(),
                    holderRef.getSequence());
            AuthorizationRoleEnum authRole = AuthorizationRoleEnum.CVCA;
            Date notBefore = new Date();
            Calendar notAfter = Calendar.getInstance();
            notAfter.add(Calendar.DAY_OF_MONTH, valdays);
            CVCertificate cvc = CertificateGenerator.createCertificate(pubKey, privKey, sigAlg, caRef,
                    holderRef, authRole, AccessRightEnum.READ_ACCESS_DG3_AND_DG4, notBefore, notAfter.getTime(),
                    "BC");
            cacert = new CardVerifiableCertificate(cvc);
        } else {
            getLogger().info("Using passed in self signed certificate.");
            cacert = cert;
        }
        try {
            cacert.verify(pubKey);
        } catch (SignatureException e) {
            getLogger().info("Can not verify self signed certificate: " + e.getMessage());
            System.exit(3); // NOPMD
        }

        Certificate[] chain = new Certificate[1];
        chain[0] = cacert;
        ejb.getCAAdminSession().importCAFromKeys(getAdmin(), caName, "foo123", chain, pubKey, privKey, null,
                null);
    } catch (ErrorAdminCommandException e) {
        throw e;
    } catch (Exception e) {
        throw new ErrorAdminCommandException(e);
    }
}

From source file:org.structr.util.StructrLicenseManager.java

/**
 *
 * @param codeSigners/*from   w  w w.j av a2 s .c  o  m*/
 * @return
 */
@Override
public boolean isValid(final CodeSigner[] codeSigners) {

    if (codeSigners != null && codeSigners.length > 0) {

        for (final CodeSigner codeSigner : codeSigners) {

            for (final Certificate cert : codeSigner.getSignerCertPath().getCertificates()) {

                try {

                    cert.verify(publicKey);
                    return true;

                } catch (Throwable ignore) {
                }
            }
        }
    }

    // none of the code signer certificates could be verified using our key => not valid
    return false;
}