Example usage for java.security.cert CertStore getCertificates

List of usage examples for java.security.cert CertStore getCertificates

Introduction

In this page you can find the example usage for java.security.cert CertStore getCertificates.

Prototype

public final Collection<? extends Certificate> getCertificates(CertSelector selector)
        throws CertStoreException 

Source Link

Document

Returns a Collection of Certificate s that match the specified selector.

Usage

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

/**
 *  ?  ?  ? ?  ?  ? ??? //from w w w.j  av a2  s.  co  m
 *  . ?  ?  ?   ?      ?  post-?
 *   ??    ?  ? ? SSL- ?
 *  ? ? ?   ?. 
 * ? ??   ? ?  ?   ? post-? ? . 
 * @param signers
 * @param clientCerts
 * @return
 * @throws CertStoreException 
 */
private boolean isBadBinOrIin(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException {
    if (signers.getSigners().size() == 0) {
        verifyErrorMsg = "    ?.";
        return true;
    }
    Iterator it = signers.getSigners().iterator();
    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) {
            verifyErrorMsg = "    ?  ? .";
            return true;
        }
        while (certIt.hasNext()) {
            X509Certificate cert = (X509Certificate) certIt.next();
            String subj = cert.getSubjectDN().getName();
            Pattern pt;
            Matcher m;
            if (typeOfRespondent.equals(TypeOfRespondent.FIRM)) {
                pt = Pattern.compile("BIN(\\d{12})");
                m = pt.matcher(subj); // get a matcher object
                if (m.find()) {
                    if (realBinIin.equals(m.group(1))) {
                        return false;
                    } else {
                        verifyErrorMsg = "? ??   ? ? ? ? '"
                                + realBinIin + "' ,   c ? '" + m.group(1) + "'. ";
                    }
                } else {
                    verifyErrorMsg = " ? c    ? '"
                            + realBinIin + "' .";
                }
            } else {
                pt = Pattern.compile("IIN(\\d{12})");
                m = pt.matcher(subj); // get a matcher object
                if (m.find()) {
                    if (realBinIin.equals(m.group(1))) {
                        return false;
                    } else {
                        verifyErrorMsg = "? ??   ? ? ? ? '"
                                + realBinIin + "' ,   c ? '" + m.group(1) + "'. ";
                    }
                } else {
                    verifyErrorMsg = " ? c    ? '"
                            + realBinIin + "' .";
                }
            }
        }
    }
    return true;
}

From source file:org.ejbca.extra.db.ExtRAMsgHelper.java

/**
 * Method used to verify signed data./*from w  ww  . j a  v  a  2 s .  c  o m*/
 * 
 * @param TrustedCACerts a Collection of trusted certificates, should contain the entire chains
 * @param TrustedCRLs a Collection of trusted CRLS, use null if no CRL check should be used.
 * @param signedData the data to verify
 * @param date the date used to check the validity against.
 * @return a ParsedSignatureResult.
 */
public static ParsedSignatureResult verifySignature(Collection cACertChain, Collection trustedCRLs,
        byte[] signedData, Date date) {
    boolean verifies = false;
    X509Certificate usercert = null;
    ParsedSignatureResult retval = new ParsedSignatureResult(false, null, null);
    byte[] content = null;

    try {
        // First verify the signature
        CMSSignedData sp = new CMSSignedData(signedData);

        CertStore certs = sp.getCertificatesAndCRLs("Collection", "BC");
        SignerInformationStore signers = sp.getSignerInfos();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ((CMSProcessableByteArray) sp.getSignedContent()).write(baos);
        content = baos.toByteArray();
        baos.close();

        Collection c = signers.getSigners();
        Iterator it = c.iterator();

        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());

            Iterator certIt = certCollection.iterator();
            usercert = (X509Certificate) certIt.next();

            boolean validalg = signer.getDigestAlgOID().equals(signAlg);

            verifies = validalg && signer.verify(usercert.getPublicKey(), "BC");

        }

        // Second validate the certificate           
        X509Certificate rootCert = null;
        Iterator iter = cACertChain.iterator();
        while (iter.hasNext()) {
            X509Certificate cert = (X509Certificate) iter.next();
            if (cert.getIssuerDN().equals(cert.getSubjectDN())) {
                rootCert = cert;
                break;
            }
        }

        if (rootCert == null) {
            throw new CertPathValidatorException("Error Root CA cert not found in cACertChain");
        }

        List list = new ArrayList();
        list.add(usercert);
        list.add(cACertChain);
        if (trustedCRLs != null) {
            list.add(trustedCRLs);
        }

        CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
        CertStore store = CertStore.getInstance("Collection", ccsp);

        //validating path
        List certchain = new ArrayList();
        certchain.addAll(cACertChain);
        certchain.add(usercert);
        CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);

        Set trust = new HashSet();
        trust.add(new TrustAnchor(rootCert, null));

        CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);
        param.addCertStore(store);
        param.setDate(date);
        if (trustedCRLs == null) {
            param.setRevocationEnabled(false);
        } else {
            param.setRevocationEnabled(true);
        }
        cpv.validate(cp, param);
        retval = new ParsedSignatureResult(verifies, usercert, content);
    } catch (Exception e) {
        log.error("Error verifying data : ", e);
    }

    return retval;
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java

/**
 * This method connects to the SCEP Server to fetch the signed SCEP Certificate.
 *
 * @param tempCert        the temporary self-signed certificate of the client required for the initial CSR
 *                        request against the SCEP Server.
 * @param certSignRequest the PKCS10 Certificate-Sign-Request that is to be sent to the SCEP Server.
 * @return the SCEP-Certificate for the client signed by the SCEP-Server.
 * @throws AgentCoreOperationException if the SCEPUrl is invalid or if the flow of sending the CSR and getting
 *                                     the signed certificate fails or if the signed certificate cannot be
 *                                     retrieved from the reply from the server.
 *//*ww w .  j  ava2 s  .  c  o  m*/
private X509Certificate getSignedCertificateFromServer(X509Certificate tempCert,
        PKCS10CertificationRequest certSignRequest) throws AgentCoreOperationException {

    X509Certificate signedSCEPCertificate = null;
    URL url;
    EnrollmentResponse enrolResponse;
    CertStore certStore;

    try {
        // The URL where we are going to request our cert from
        url = new URL(this.SCEPUrl);

        /*  // This is called when we get the certificate for our CSR signed by CA
        // Implement this handler to check the CA cert in prod. We can do cert pinning here
        CallbackHandler cb = new CallbackHandler() {
        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated
            methods, choose Tools | Templates.
        }
        };*/

        // I did not implement any verification of the CA cert. DO NOT DO THAT.
        // For testing this is OK, in Prod make sure to VERIFY the CA
        CertificateVerifier ocv = new OptimisticCertificateVerifier();

        // Instantiate our SCEP client
        Client scepClient = new Client(url, ocv);

        // Submit our cert for signing. iosTrustpoint allows the client to specify
        // the SCEP CA to issue the request against, if there are multiple CAs
        enrolResponse = scepClient.enrol(tempCert, this.privateKey, certSignRequest);

        // Verify we got what we want, and just print out the cert.
        certStore = enrolResponse.getCertStore();

        for (java.security.cert.Certificate x509Certificate : certStore.getCertificates(null)) {
            if (log.isDebugEnabled()) {
                log.debug(x509Certificate.toString());
            }
            signedSCEPCertificate = (X509Certificate) x509Certificate;
        }

    } catch (MalformedURLException ex) {
        String errorMsg = "Could not create valid URL from given SCEP URI: " + SCEPUrl;
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, ex);
    } catch (TransactionException | ClientException e) {
        String errorMsg = "Enrollment process to SCEP Server at: " + SCEPUrl + " failed.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertStoreException e) {
        String errorMsg = "Could not retrieve [Signed-Certificate] from the response message from SCEP-Server.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return signedSCEPCertificate;
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.enrollment.EnrollmentManager.java

/**
 * Gets the Public Key of the SCEP-Server and initializes it for later use. This method contacts the SCEP Server
 * and fetches its CA Cert and extracts the Public Key of the server from the received reply.
 *
 * @return the public key of the SCEP Server which is to be used to encrypt pyloads.
 * @throws AgentCoreOperationException if the SCEPUrl is invalid or if the flow of sending the CSR and getting
 *                                     the signed certificate fails or if the signed certificate cannot be
 *                                     retrieved from the reply from the server.
 */// www.  j av a2  s  .c om
private PublicKey initPublicKeyOfServer() throws AgentCoreOperationException {
    URL url;
    CertStore certStore;
    PublicKey serverCertPublicKey = null;

    try {
        // The URL where we are going to request our cert from
        url = new URL(this.SCEPUrl);

        /*  // This is called when we get the certificate for our CSR signed by CA
        // Implement this handler to check the CA cert in prod. We can do cert pinning here
        CallbackHandler cb = new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated
                methods, choose Tools | Templates.
        }
        };*/

        // I did not implement any verification of the CA cert. DO NOT DO THAT.
        // For testing this is OK, in Prod make sure to VERIFY the CA
        CertificateVerifier ocv = new OptimisticCertificateVerifier();

        // Instantiate our SCEP client
        Client scepClient = new Client(url, ocv);

        // Get the CA capabilities. For some reason the IOS router does not return
        // correct information here. Do not trust it. Should return SHA1withRSA for
        // strongest hash and sig. Returns MD5.

        if (log.isDebugEnabled()) {
            Capabilities cap = scepClient.getCaCapabilities();
            log.debug(String.format(
                    "\nStrongestCipher: %s,\nStrongestMessageDigest: %s,\nStrongestSignatureAlgorithm: %s,"
                            + "\nIsRenewalSupported: %s,\nIsRolloverSupported: %s",
                    cap.getStrongestCipher(), cap.getStrongestMessageDigest(),
                    cap.getStrongestSignatureAlgorithm(), cap.isRenewalSupported(), cap.isRolloverSupported()));
        }

        certStore = scepClient.getCaCertificate();

        for (Certificate cert : certStore.getCertificates(null)) {
            if (cert instanceof X509Certificate) {
                if (log.isDebugEnabled()) {
                    log.debug(((X509Certificate) cert).getIssuerDN().getName());
                }

                //TODO: Need to identify the correct certificate.
                // I have chosen the CA cert based on its BasicConstraint criticality being set to "true"
                if (((X509CertImpl) cert).getBasicConstraintsExtension().isCritical()) {
                    serverCertPublicKey = cert.getPublicKey();
                }
            }
        }

    } catch (MalformedURLException ex) {
        String errorMsg = "Could not create valid URL from given SCEP URI: " + SCEPUrl;
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, ex);
    } catch (ClientException e) {
        String errorMsg = "Could not retrieve [Server-Certificate] from the SCEP-Server.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertStoreException e) {
        String errorMsg = "Could not retrieve [Server-Certificates] from the response message from SCEP-Server.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return serverCertPublicKey;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager.java

/**
 * This method connects to the SCEP Server to fetch the signed SCEP Certificate.
 *
 * @param tempCert        the temporary self-signed certificate of the client required for the initial CSR
 *                        request against the SCEP Server.
 * @param certSignRequest the PKCS10 Certificate-Sign-Request that is to be sent to the SCEP Server.
 * @return the SCEP-Certificate for the client signed by the SCEP-Server.
 * @throws AgentCoreOperationException if the SCEPUrl is invalid or if the flow of sending the CSR and getting
 *                                     the signed certificate fails or if the signed certificate cannot be
 *                                     retrieved from the reply from the server.
 *///from   w  w  w. j  a v a2 s.c  om
private X509Certificate getSignedCertificateFromServer(X509Certificate tempCert,
        PKCS10CertificationRequest certSignRequest) throws AgentCoreOperationException {

    X509Certificate signedSCEPCertificate = null;
    URL url;
    EnrollmentResponse enrolResponse;
    CertStore certStore;

    try {
        // The URL where we are going to request our cert from
        url = new URL(this.SCEPUrl);

        /*  // This is called when we get the certificate for our CSR signed by CA
        // Implement this handler to check the CA cert in prod. We can do cert pinning here
        CallbackHandler cb = new CallbackHandler() {
        @Override
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated
            methods, choose Tools | Templates.
        }
        };*/

        // Implement verification of the CA cert. VERIFY the CA
        CertificateVerifier ocv = new OptimisticCertificateVerifier();

        // Instantiate our SCEP client
        Client scepClient = new Client(url, ocv);

        // Submit our cert for signing. SCEP server should allow the client to specify
        // the SCEP CA to issue the request against, if there are multiple CAs
        enrolResponse = scepClient.enrol(tempCert, this.privateKey, certSignRequest);

        // Verify we got what we want, and just print out the cert.
        certStore = enrolResponse.getCertStore();

        for (Certificate x509Certificate : certStore.getCertificates(null)) {
            if (log.isDebugEnabled()) {
                log.debug(x509Certificate.toString());
            }
            signedSCEPCertificate = (X509Certificate) x509Certificate;
        }

    } catch (MalformedURLException ex) {
        String errorMsg = "Could not create valid URL from given SCEP URI: " + SCEPUrl;
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, ex);
    } catch (TransactionException | ClientException e) {
        String errorMsg = "Enrollment process to SCEP Server at: " + SCEPUrl + " failed.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertStoreException e) {
        String errorMsg = "Could not retrieve [Signed-Certificate] from the response message from SCEP-Server.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return signedSCEPCertificate;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.enrollment.EnrollmentManager.java

/**
 * Gets the Public Key of the SCEP-Server and initializes it for later use. This method contacts the SCEP Server
 * and fetches its CA Cert and extracts the Public Key of the server from the received reply.
 *
 * @return the public key of the SCEP Server which is to be used to encrypt pyloads.
 * @throws AgentCoreOperationException if the SCEPUrl is invalid or if the flow of sending the CSR and getting
 *                                     the signed certificate fails or if the signed certificate cannot be
 *                                     retrieved from the reply from the server.
 *//*from   w  w  w  . j av a  2  s  .  com*/
private PublicKey initPublicKeyOfServer() throws AgentCoreOperationException {
    URL url;
    CertStore certStore;
    PublicKey serverCertPublicKey = null;

    try {
        // The URL where we are going to request our cert from
        url = new URL(this.SCEPUrl);

        /*  // This is called when we get the certificate for our CSR signed by CA
        // Implement this handler to check the CA cert in prod. We can do cert pinning here
        CallbackHandler cb = new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated
                methods, choose Tools | Templates.
        }
        };*/

        // Implement verification of the CA cert. VERIFY the CA
        CertificateVerifier ocv = new OptimisticCertificateVerifier();

        // Instantiate our SCEP client
        Client scepClient = new Client(url, ocv);

        // Get the CA capabilities. Should return SHA1withRSA for strongest hash and sig. Returns MD5.
        if (log.isDebugEnabled()) {
            Capabilities cap = scepClient.getCaCapabilities();
            log.debug(String.format(
                    "\nStrongestCipher: %s,\nStrongestMessageDigest: %s,\nStrongestSignatureAlgorithm: %s,"
                            + "\nIsRenewalSupported: %s,\nIsRolloverSupported: %s",
                    cap.getStrongestCipher(), cap.getStrongestMessageDigest(),
                    cap.getStrongestSignatureAlgorithm(), cap.isRenewalSupported(), cap.isRolloverSupported()));
        }

        certStore = scepClient.getCaCertificate();

        for (Certificate cert : certStore.getCertificates(null)) {
            if (cert instanceof X509Certificate) {
                if (log.isDebugEnabled()) {
                    log.debug(((X509Certificate) cert).getIssuerDN().getName());
                }

                // I have chosen the CA cert based on its BasicConstraintExtension "is_ca" being set to "true"
                // This is because the returned keystore may contain many certificates including RAs.
                if (((Boolean) ((X509CertImpl) cert).getBasicConstraintsExtension()
                        .get(CERT_IS_CA_EXTENSION))) {
                    serverCertPublicKey = cert.getPublicKey();
                }
            }
        }

    } catch (MalformedURLException ex) {
        String errorMsg = "Could not create valid URL from given SCEP URI: " + SCEPUrl;
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, ex);
    } catch (ClientException e) {
        String errorMsg = "Could not retrieve [Server-Certificate] from the SCEP-Server.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertStoreException e) {
        String errorMsg = "Could not retrieve [Server-Certificates] from the response message from SCEP-Server.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Error occurred whilst trying to get property ['is_ca'] from the retreived Certificates";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return serverCertPublicKey;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

/**
 * Gets the Public Key of the SCEP-Server and initializes it for later use. This method contacts the SCEP Server
 * and fetches its CA Cert and extracts the Public Key of the server from the received reply.
 *
 * @return the public key of the SCEP Server which is to be used to encrypt pyloads.
 * @throws AgentCoreOperationException if the SCEPUrl is invalid or if the flow of sending the CSR and getting
 *                                     the signed certificate fails or if the signed certificate cannot be
 *                                     retrieved from the reply from the server.
 *///from   www.  j  ava2  s .c o  m
private PublicKey initPublicKeyOfServer() throws AgentCoreOperationException {
    URL url;
    CertStore certStore;
    PublicKey serverCertPublicKey = null;

    try {
        // The URL where we are going to request our cert from
        url = new URL(this.SCEPUrl);

        /*  // This is called when we get the certificate for our CSR signed by CA
        // Implement this handler to check the CA cert in prod. We can do cert pinning here
        CallbackHandler cb = new CallbackHandler() {
            @Override
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated
                methods, choose Tools | Templates.
        }
        };*/

        // Implement verification of the CA cert. VERIFY the CA
        CertificateVerifier ocv = new OptimisticCertificateVerifier();

        // Instantiate our SCEP client
        Client scepClient = new Client(url, ocv);

        // Get the CA capabilities. Should return SHA1withRSA for strongest hash and sig. Returns MD5.
        if (log.isDebugEnabled()) {
            Capabilities cap = scepClient.getCaCapabilities();
            log.debug(String.format(
                    "\nStrongestCipher: %s,\nStrongestMessageDigest: %s,\nStrongestSignatureAlgorithm: %s,"
                            + "\nIsRenewalSupported: %s,\nIsRolloverSupported: %s",
                    cap.getStrongestCipher(), cap.getStrongestMessageDigest(),
                    cap.getStrongestSignatureAlgorithm(), cap.isRenewalSupported(), cap.isRolloverSupported()));
        }

        certStore = scepClient.getCaCertificate();

        for (Certificate cert : certStore.getCertificates(null)) {
            if (cert instanceof X509Certificate) {
                if (log.isDebugEnabled()) {
                    log.debug(((X509Certificate) cert).getIssuerDN().getName());
                }

                // I have chosen the CA cert based on its BasicConstraintExtension "is_ca" being set to "true"
                // This is because the returned keystore may contain many certificates including RAs.
                if (((Boolean) ((X509CertImpl) cert).getBasicConstraintsExtension()
                        .get(CERT_IS_CA_EXTENSION))) {
                    serverCertPublicKey = cert.getPublicKey();
                    storeCertificateToStore(AgentConstants.SERVER_CA_CERT_ALIAS, cert);
                }
            }
        }

    } catch (MalformedURLException ex) {
        String errorMsg = "Could not create valid URL from given SCEP URI: " + SCEPUrl;
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, ex);
    } catch (ClientException e) {
        String errorMsg = "Could not retrieve [Server-Certificate] from the SCEP-Server.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (CertStoreException e) {
        String errorMsg = "Could not retrieve [Server-Certificates] from the response message from SCEP-Server.";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Error occurred whilst trying to get property ['is_ca'] from the retreived Certificates";
        log.error(errorMsg);
        throw new AgentCoreOperationException(errorMsg, e);
    }

    return serverCertPublicKey;
}

From source file:org.yawlfoundation.yawl.digitalSignature.DigitalSignature.java

public boolean checkSignature(byte[] Document) {
    try {/* ww  w .j  av a 2s.c o m*/
        System.out.println("Beginning of Checking XmlSignature:");
        System.out.println(Document);

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        // extract the Signed Fingerprint data
        CMSSignedData signature = new CMSSignedData(Document);
        System.out.println("Beginning of Checking XmlSignature:");

        SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator()
                .next();
        System.out.println("Beginning of Checking XmlSignature:");

        // Get from the collection the appropriate registered certificate
        CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC");
        Iterator iter = cs.getCertificates(signer.getSID()).iterator();
        System.out.println("Beginning of Checking XmlSignature:");
        X509Certificate certificate = (X509Certificate) iter.next();
        System.out.println("Beginning of Checking XmlSignature:");
        // get the contents of the document
        CMSProcessable sg = signature.getSignedContent();
        byte[] data = (byte[]) sg.getContent();
        String content = new String(data);

        //convert the document content to a valid xml document for YAWL
        org.w3c.dom.Document XMLNode = ConvertStringToDocument(content);
        org.jdom2.input.DOMBuilder builder = new org.jdom2.input.DOMBuilder();
        Doc = builder.build(XMLNode);

        //Check the document
        System.out.println("xml to Sign:");
        System.out.println(JDOMUtil.documentToString(Doc));

        // get the name of the signer
        _Name = certificate.getSubjectDN().getName().split("(=|, )", -1).toString();
        //return the result of the signature checking
        return signer.verify(certificate, "BC");

    } catch (Exception e) {
        System.out.println("Test error");
        e.printStackTrace();
        return false;
    }

}

From source file:test.integ.be.fedict.trust.TSATest.java

@Test
public void testTSA() throws Exception {

    // setup//from   w  w  w . ja v  a2 s .  co m
    TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator();
    requestGen.setCertReq(true);
    TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100));
    byte[] requestData = request.getEncoded();

    HttpClient httpClient = new HttpClient();
    httpClient.getHostConfiguration().setProxy("proxy.yourict.net", 8080);
    PostMethod postMethod = new PostMethod(tsa_location);
    postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query"));

    // operate
    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
        LOG.error("Error contacting TSP server " + tsa_location);
        throw new Exception("Error contacting TSP server " + tsa_location);
    }

    TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream());
    postMethod.releaseConnection();

    CertStore certStore = tspResponse.getTimeStampToken().getCertificatesAndCRLs("Collection", "BC");

    Collection<? extends Certificate> certificates = certStore.getCertificates(null);
    List<X509Certificate> certificateChain = new LinkedList<X509Certificate>();
    for (Certificate certificate : certificates) {
        LOG.debug("certificate: " + certificate.toString());
        certificateChain.add(0, (X509Certificate) certificate);
    }

    LOG.debug("token received");
    // send token to trust service
    XKMS2Client client = new XKMS2Client("https://www.e-contract.be/eid-trust-service-ws/xkms2");
    client.setProxy("proxy.yourict.net", 8080);
    client.validate(TrustServiceDomains.BELGIAN_TSA_TRUST_DOMAIN, certificateChain, true);
}

From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java

/**
 * CMS signature with external data and embedded certificate. The CMS only
 * contains the signature, signing certificate and some certificate
 * selector.//from  w ww .  j a v  a  2 s  .  com
 * 
 * @throws Exception
 */
@Test
public void testCmsSignatureWithCertificate() throws Exception {
    // setup
    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=Test", notBefore, notAfter);
    byte[] toBeSigned = "hello world".getBytes();

    // operate
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    /*
     * addSigner requires the certificate to be able to calculate the key
     * selector.
     */
    generator.addSigner(keyPair.getPrivate(), certificate, CMSSignedDataGenerator.DIGEST_SHA1);
    List<X509Certificate> certList = new LinkedList<X509Certificate>();
    certList.add(certificate);
    CertStore certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList));
    generator.addCertificatesAndCRLs(certStore);
    CMSProcessable content = new CMSProcessableByteArray(toBeSigned);
    CMSSignedData signedData = generator.generate(content, false, (String) null);

    byte[] cmsSignature = signedData.getEncoded();
    LOG.debug("CMS signature: " + ASN1Dump.dumpAsString(new ASN1StreamParser(cmsSignature).readObject()));

    // verify
    signedData = new CMSSignedData(content, cmsSignature);
    certStore = signedData.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME);
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator<SignerInformation> iter = signers.getSigners().iterator();
    while (iter.hasNext()) {
        SignerInformation signer = iter.next();
        SignerId signerId = signer.getSID();
        LOG.debug("signer: " + signerId);
        X509CertSelector signerConstraints = new JcaX509CertSelectorConverter().getCertSelector(signerId);
        LOG.debug("signerConstraints: " + signerConstraints);
        assertTrue(signerConstraints.match(certificate));
        assertTrue(signer.verify(keyPair.getPublic(), BouncyCastleProvider.PROVIDER_NAME));

        X509Certificate storedCert = (X509Certificate) certStore // TODO FIXME
                .getCertificates(signerConstraints).iterator().next();
        assertEquals(certificate, storedCert);
    }
    LOG.debug("content type: " + signedData.getSignedContentTypeOID());
}