Example usage for org.bouncycastle.cert.jcajce JcaCertStoreBuilder JcaCertStoreBuilder

List of usage examples for org.bouncycastle.cert.jcajce JcaCertStoreBuilder JcaCertStoreBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaCertStoreBuilder JcaCertStoreBuilder.

Prototype

JcaCertStoreBuilder

Source Link

Usage

From source file:CAModulePackage.CertificateHelper.java

/**
 * Validates the certificate chain/path.
 * @param TACerts - Set of Certificates that are the Trust Anchors.
 * @param certificates - List of certificates in the chain/path.
 * @return True if the path is valid, False if it's not.
 *//*w  ww  . j  a v  a  2s . c  o  m*/
public static boolean validateCertificatePath(Set<X509CertificateHolder> TACerts,
        ArrayList<X509CertificateHolder> certificates) {
    Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();

    //Convert all our TA Certificates to normal X509Certificates.
    for (X509CertificateHolder cert : TACerts) {

        X509Certificate tempCert = null;
        try {
            tempCert = (new JcaX509CertificateConverter()).getCertificate(cert);
        } catch (CertificateException e) {
            e.printStackTrace();
        }
        trustAnchors.add(new TrustAnchor(tempCert, null));
    }

    PKIXBuilderParameters params = null;
    try {
        params = new PKIXBuilderParameters(trustAnchors, new X509CertSelector());
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }

    //Build a Certificate Store with the certificates from the chain.
    JcaCertStoreBuilder builder = new JcaCertStoreBuilder();
    for (X509CertificateHolder c : certificates) {
        System.out.println("---Chain Cert---");
        System.out.println("SUBJ: " + c.getSubject().toString());
        System.out.println("ISSUER: " + c.getIssuer().toString());
        builder.addCertificate(c);
    }

    //Add the store to the build parameters
    try {
        params.addCertStore(builder.build());
    } catch (GeneralSecurityException ex) {
        Logger.getLogger(CertificateHelper.class.getName()).log(Level.SEVERE, null, ex);
    }

    params.setRevocationEnabled(false);

    //Build the certificate chain - if a result is thrown, we failed.
    PKIXCertPathBuilderSpi pathBuilder = new PKIXCertPathBuilderSpi();
    PKIXCertPathBuilderResult resultPath = null;
    try {
        resultPath = (PKIXCertPathBuilderResult) pathBuilder.engineBuild(params);
    } catch (CertPathBuilderException e) {
        return false;
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    }

    return true;
}

From source file:com.guardtime.ksi.trust.JKSTrustStore.java

License:Apache License

/**
 * This method is used to check if certificate is trusted or not.
 *
 * @param certificate/*from   w  w  w. j a  va  2 s .  c om*/
 *         instance of PKI X.509 certificate. not null.
 * @param certStore
 *         additional certificates to be used to check if certificate chain is trusted or not.
 * @return true if certificate is trusted, false otherwise
 * @throws CryptoException
 *         will be thrown when exception occurs turning certificate path building
 */
public boolean isTrusted(X509Certificate certificate, Store certStore) throws CryptoException {
    try {
        if (certificate == null) {
            throw new CryptoException("Invalid input parameter. Certificate can not be null");
        }
        LOGGER.info("Checking if certificate with subjectDN={} is trusted", certificate.getSubjectDN());
        Store certificateStore = certStore;
        if (certificateStore == null) {
            certificateStore = new JcaCertStore(new ArrayList());
        }
        checkEmail(certSelector, certificate);

        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(certificate);

        CertStore pkixParamsCertStore = new JcaCertStoreBuilder().addCertificates(certificateStore).build();

        PKIXBuilderParameters buildParams = new PKIXBuilderParameters(keyStore, selector);
        buildParams.addCertStore(pkixParamsCertStore);
        buildParams.setRevocationEnabled(false);

        CertPathBuilder builder = CertPathBuilder.getInstance(ALGORITHM_PKIX);
        PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(buildParams);

        // Build certificate path
        CertPath certPath = result.getCertPath();

        // Set validation parameters
        PKIXParameters params = new PKIXParameters(keyStore);
        params.setRevocationEnabled(false);

        // Validate certificate path
        CertPathValidator validator = CertPathValidator.getInstance(ALGORITHM_PKIX);
        validator.validate(certPath, params);
        return true;
    } catch (CertPathValidatorException e) {
        LOGGER.debug("Cert path validation failed", e);
        return false;
    } catch (CertPathBuilderException e) {
        LOGGER.debug("Cert path building failed", e);
        return false;
    } catch (GeneralSecurityException e) {
        throw new CryptoException("General security error occurred. " + e.getMessage(), e);
    }
}

From source file:id.govca.detachedsignature.CMSController.java

public boolean VerifyCMS(CMSSignedData signedData, String content_digest) throws IOException, CMSException,
        CertificateException, OperatorCreationException, UnmatchedSignatureException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        StringFormatException, ParseException, GeneralSecurityException {
    rootCertCandidate = null;//from   www  .  java2  s  .c om

    Security.addProvider(new BouncyCastleProvider());

    byte[] dataku = (byte[]) signedData.getSignedContent().getContent();
    System.out.format("%-32s%s\n", "Base64 of Signed Content", Hex.toHexString(dataku));

    Store store = signedData.getCertificates();

    CertStore certsAndCRLs = new JcaCertStoreBuilder().setProvider("BC")
            .addCertificates(signedData.getCertificates()).build();

    // Verify signature
    SignerInformationStore signers = signedData.getSignerInfos();
    Collection c = signers.getSigners();
    System.out.format("%-32s%s\n", "Number of Signers", c.size());

    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        AttributeTable att = signer.getSignedAttributes();

        Attribute mdAtt = att.get(CMSAttributes.messageDigest);
        ASN1Primitive asp = mdAtt.getAttrValues().getObjectAt(0).toASN1Primitive();
        byte[] hasil = asp.getEncoded("DER");

        System.out.format("%-32s%s\n", "Digest of Signature", Hex.toHexString(hasil));

        Collection certCollection = store.getMatches(signer.getSID());
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC");

        ArrayList<X509CertificateHolder> listCertDatFirm = new ArrayList(store.getMatches(null));
        System.out.format("%-32s%d\n", "Number of cert Holders All", listCertDatFirm.size());

        try {
            verifyChain(listCertDatFirm);
        } catch (CertificateVerificationException ex) {
            System.out.println("CERTIFICATE CHAIN VERIFICATION FAILED");
            Logger.getLogger(CMSController.class.getName()).log(Level.SEVERE, null, ex);
            throw new UnmatchedSignatureException("Certificate Chain verification failed");
        }
        System.out.println("CERTIFICATE CHAIN VERIFIED");

        Collection<X509CertificateHolder> holders = store.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider()).getCertificate(certHolder);

        Principal princ = certFromSignedData.getIssuerDN();

        //Get Signer Name
        Principal p = certFromSignedData.getSubjectDN();
        System.out.format("%-32s%s\n", "Signer Distinguished Name", p.getName());

        this.setDN_fields(StringHelper.DNFieldsMapper(p.getName()));

        //Get Signing Time
        org.bouncycastle.asn1.cms.Attribute signingTime = att
                .get(new ASN1ObjectIdentifier("1.2.840.113549.1.9.5"));
        String asn1time = signingTime.getAttrValues().toString();
        System.out.format("%-32s%s\n", "Signing Time (RAW format)", asn1time);

        Date signtime = StringHelper.ASN1DateParser(asn1time);
        SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
        String formattedDate = formatter.format(signtime);
        System.out.format("%-32s%s\n", "Signing Time (Pretty format)", formattedDate);

        PublicKey pubkey = certFromSignedData.getPublicKey();

        if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider())
                .build(certFromSignedData))) {
            System.out.println("SIGNATURE VERIFIED <BY BOUNCY CASTLE STANDARD>");
        } else {
            System.out.println("SIGNATURE VERIFICATION <BY BOUNCY CASTLE STANDARD> FAILED");
            throw new UnmatchedSignatureException(
                    "Signature verification failed, probably the signature (CMS) has been altered!");
        }

        Cipher RSADecrypter;

        RSADecrypter = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

        //Initialize the Cipher using our the first key in the keystore  works fine for both
        RSADecrypter.init(Cipher.DECRYPT_MODE, pubkey);
        byte[] try_decrypt = RSADecrypter.doFinal(dataku);

        String decrypt_result = Hex.toHexString(try_decrypt);
        //Because there is magic number for hash algorithm at the beginning of the string,
        //we only need the last 64 characters from the decryption result
        String sanitized_decrypt_result = decrypt_result.substring(decrypt_result.length() - 64);

        System.out.format("%-32s%s\n", "Decryption Result", decrypt_result);
        System.out.format("%-32s%s\n", "Sanitized Decryption Result", sanitized_decrypt_result);

        if (!content_digest.equals(sanitized_decrypt_result)) {
            System.out.println("CONTENT DIGEST VERIFICATION FAILED");
            throw new UnmatchedSignatureException(
                    "Content digest verification failed, probably the content has been altered!");
        }
        System.out.println("CONTENT DIGEST VERIFIED");

        try {
            RootCertChecker rc = new RootCertChecker();

            rc.checkCertificate(rootCertCandidate, getRoot_cert_path());
        } catch (FileNotFoundException | InvalidKeyException | NoSuchAlgorithmException
                | NoSuchProviderException | SignatureException | CertificateException ex) {
            System.out.println("ROOT CERT VERIFICATION FAILED");
            throw new UnmatchedSignatureException("The System does not recognized this root Certificate");
        }
        System.out.println("ROOT CERTIFICATE VERIFIED");

    }

    return true;
}

From source file:org.apache.james.transport.KeyStoreHolder.java

License:Apache License

/**
 * Verifies the signature of a SMIME message.
 * /*from  w w w  . ja v a 2s  .  co m*/
 * It checks also if the signer's certificate is trusted using the loaded
 * keystore as trusted certificate store.
 * 
 * @param signed
 *            the signed mail to check.
 * @return a list of SMIMESignerInfo which keeps the data of each mail
 *         signer.
 * @throws Exception
 * @throws MessagingException
 */
public List<SMIMESignerInfo> verifySignatures(SMIMESigned signed) throws Exception {

    CertStore certs = new JcaCertStoreBuilder().addCertificates(signed.getCertificates())
            .addCRLs(signed.getCRLs()).build();
    SignerInformationStore siginfo = signed.getSignerInfos();
    Collection<SignerInformation> sigCol = siginfo.getSigners();
    List<SMIMESignerInfo> result = new ArrayList<SMIMESignerInfo>(sigCol.size());
    // I iterate over the signer collection 
    // checking if the signatures put
    // on the message are valid.
    for (SignerInformation info : sigCol) {
        // I get the signer's certificate
        X509CertificateHolderSelector x509CertificateHolderSelector = new X509CertificateHolderSelector(
                info.getSID().getSubjectKeyIdentifier());
        X509CertSelector certSelector = new JcaX509CertSelectorConverter()
                .getCertSelector(x509CertificateHolderSelector);
        @SuppressWarnings("unchecked")
        Collection<X509Certificate> certCollection = (Collection<X509Certificate>) certs
                .getCertificates(certSelector);
        if (!certCollection.isEmpty()) {
            X509Certificate signerCert = certCollection.iterator().next();
            // The issuer's certifcate is searched in the list of trusted certificate.
            CertPath path = verifyCertificate(signerCert, certs, keyStore);

            try {
                // if the signature is valid the SMIMESignedInfo is 
                // created using "true" as last argument. If it is  
                // invalid an exception is thrown by the "verify" method
                // and the SMIMESignerInfo is created with "false".
                //
                // The second argument "path" is not null if the 
                // certificate can be trusted (it can be connected 
                // by a chain of trust to a trusted certificate), null
                // otherwise.
                if (info.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BC).build(signerCert))) {
                    result.add(new SMIMESignerInfo(signerCert, path, true));
                }
            } catch (Exception e) {
                result.add(new SMIMESignerInfo(signerCert, path, false));
            }
        }
    }
    return result;
}

From source file:org.cryptoworkshop.ximix.client.verify.SignedDataVerifier.java

License:Apache License

private PKIXCertPathBuilderResult checkCertPath(SignerId signerId, Store certs)
        throws IOException, GeneralSecurityException {
    CertStore store = new JcaCertStoreBuilder().setProvider("BC").addCertificates(certs).build();

    CertPathBuilder pathBuilder = CertPathBuilder.getInstance("PKIX", "BC");
    X509CertSelector targetConstraints = new X509CertSelector();

    targetConstraints.setIssuer(signerId.getIssuer().getEncoded());
    targetConstraints.setSerialNumber(signerId.getSerialNumber());

    PKIXBuilderParameters params = new PKIXBuilderParameters(
            Collections.singleton(new TrustAnchor(trustAnchor, null)), targetConstraints);

    params.addCertStore(store);//from   w ww  .  j av a  2 s  .c om
    params.setRevocationEnabled(false); // TODO: CRLs?

    return (PKIXCertPathBuilderResult) pathBuilder.build(params);
}

From source file:org.ejbca.batchenrollmentgui.BatchEnrollmentGUIView.java

License:Open Source License

private static List<X509Certificate> validateChain(X509Certificate signerCert, Store certs,
        Collection<Certificate> trustedCerts) throws GeneralSecurityException {

    final Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();
    for (Certificate cert : trustedCerts) {
        if (cert instanceof X509Certificate) {
            anchors.add(new TrustAnchor((X509Certificate) cert, null));
        }//from  w w w  . j a v a2s.  com
    }

    final CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX");
    X509CertSelector targetConstraints = new X509CertSelector();
    targetConstraints.setCertificate(signerCert);
    PKIXBuilderParameters cpbParams = new PKIXBuilderParameters(anchors, targetConstraints);
    JcaCertStoreBuilder jcaCertStoreBuilder = new JcaCertStoreBuilder();
    jcaCertStoreBuilder.addCertificates(certs);

    cpbParams.addCertStore(jcaCertStoreBuilder.build());
    cpbParams.setRevocationEnabled(false);

    // Build path
    PKIXCertPathBuilderResult cpbResult = (PKIXCertPathBuilderResult) cpb.build(cpbParams);
    CertPath certPath = cpbResult.getCertPath();

    // Validate path
    final CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
    final PKIXParameters params = new PKIXParameters(anchors);
    params.setSigProvider("BC");
    params.setRevocationEnabled(false);

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(certPath, params);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Found trust anchor: " + result.getTrustAnchor());
    }

    List<X509Certificate> signerChain = new ArrayList<X509Certificate>();

    for (Certificate cert : certPath.getCertificates()) {
        signerChain.add((X509Certificate) cert);
    }
    if (signerChain.size() > 0) {
        signerChain.add(result.getTrustAnchor().getTrustedCert());
    }

    return signerChain;
}