Example usage for org.bouncycastle.cms CMSSignedData getSignedContent

List of usage examples for org.bouncycastle.cms CMSSignedData getSignedContent

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedData getSignedContent.

Prototype

public CMSTypedData getSignedContent() 

Source Link

Usage

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESChecker.java

License:Open Source License

/**
 * Extracts the signed content from the digital signature structure, if it
 * is a signature with attached content.
 *
 * @param signed/*  www .j  av  a2 s .c om*/
 *            Signature and signed content.
 * @param validateOnExtract
 *            TRUE (to execute validation) or FALSE (not execute validation)
 * 
 * @return content for attached signature
 */
@Override
public byte[] getAttached(byte[] signed, boolean validateOnExtract) {

    byte[] result = null;

    if (validateOnExtract) {
        this.check(null, signed);
    }

    CMSSignedData signedData = null;
    try {
        signedData = new CMSSignedData(signed);
    } catch (CMSException exception) {
        throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), exception);
    }

    try {
        CMSProcessable contentProcessable = signedData.getSignedContent();
        if (contentProcessable != null) {
            result = (byte[]) contentProcessable.getContent();
        } else {
            logger.info(cadesMessagesBundle.getString("error.get.content.empty"));
        }
    } catch (Exception exception) {
        throw new SignerException(cadesMessagesBundle.getString("error.get.content.pkcs7"), exception);
    }

    return result;

}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java

License:Open Source License

/**
 * Extracts the signed content from the digital signature structure, if it
 * is a signature with attached content.
 *
 * @param signed//from  ww w. ja v  a  2s. c o  m
 *            Signature and signed content.
 * @param validateOnExtract
 *            TRUE (to execute validation) or FALSE (not execute validation)
 * 
 * @return content for attached signature
 * @deprecated moved to CadESChecker
 */
@Override
public byte[] getAttached(byte[] signed, boolean validateOnExtract) {

    byte[] result = null;

    if (validateOnExtract) {
        this.check(null, signed);
    }

    CMSSignedData signedData = null;
    try {
        signedData = new CMSSignedData(signed);
    } catch (CMSException exception) {
        throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), exception);
    }

    try {
        CMSProcessable contentProcessable = signedData.getSignedContent();
        if (contentProcessable != null) {
            result = (byte[]) contentProcessable.getContent();
        }
    } catch (Exception exception) {
        throw new SignerException(cadesMessagesBundle.getString("error.get.content.pkcs7"), exception);
    }

    return result;

}

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

License:Open Source License

@SuppressWarnings("unchecked")
private static CMSValidationResult validateCMS(final CMSSignedData signedData,
        final Collection<Certificate> trustedCerts) {

    final CMSValidationResult result = new CMSValidationResult();

    try {//from www  .j a va2s . c  o m
        final ContentInfo ci = signedData.toASN1Structure();
        if (LOG.isDebugEnabled()) {
            LOG.debug("ci.content: " + ci.getContent() + "\n" + "signedContent: "
                    + signedData.getSignedContent());
        }

        final Object content = signedData.getSignedContent().getContent();

        if (content instanceof byte[]) {
            result.setContent((byte[]) content);
        }

        Store certs = signedData.getCertificates();
        SignerInformationStore signers = signedData.getSignerInfos();
        for (Object o : signers.getSigners()) {
            if (o instanceof SignerInformation) {
                SignerInformation si = (SignerInformation) o;

                if (LOG.isDebugEnabled()) {
                    LOG.debug("*** SIGNATURE: " + "\n" + si.getSID());
                }

                final Collection<X509CertificateHolder> signerCerts = (Collection<X509CertificateHolder>) certs
                        .getMatches(si.getSID());

                if (LOG.isDebugEnabled()) {
                    LOG.debug("signerCerts: " + signerCerts);
                }
                JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
                for (X509CertificateHolder signerCert : signerCerts) {
                    final X509Certificate signerX509Cert = jcaX509CertificateConverter
                            .getCertificate(signerCert);

                    // Verify the signature
                    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
                    JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
                            calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
                    boolean consistent = si
                            .verify(jcaSignerInfoVerifierBuilder.build(signerX509Cert.getPublicKey()));
                    if (consistent) {

                        if (LOG.isDebugEnabled()) {
                            LOG.debug((consistent ? "Consistent" : "Inconsistent") + " signature from "
                                    + signerX509Cert.getSubjectDN() + " issued by "
                                    + signerX509Cert.getIssuerDN());
                        }

                        result.setValidSignature(consistent);

                        try {
                            final List<X509Certificate> signerChain = validateChain(signerX509Cert, certs,
                                    trustedCerts);

                            result.setValidChain(true);
                            result.setSignerChain(signerChain);

                            JOptionPane.showMessageDialog(null,
                                    "Found valid signature from \"" + signerX509Cert.getSubjectDN() + "\"",
                                    "Signature check", JOptionPane.INFORMATION_MESSAGE);

                        } catch (CertPathBuilderException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, "Error: Certificate path:\n" + ex.getMessage(),
                                    "Signature check", JOptionPane.ERROR_MESSAGE);
                        } catch (CertPathValidatorException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null,
                                    "Error: Certificate validation:\n" + ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (InvalidAlgorithmParameterException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (NoSuchAlgorithmException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (GeneralSecurityException e) {
                            //Crappy catch-all, but not much to do due to underlying BC-code
                            result.setError(e.getMessage());
                            JOptionPane.showMessageDialog(null, e.getMessage(),
                                    "Error: Certificate validation:\n", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        result.setError("Inconsistent signature!");
                        JOptionPane.showMessageDialog(null, "Error: Inconsisten signature!", "Signature check",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }

            }
        }

    } catch (CMSException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    } catch (OperatorCreationException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    } catch (CertificateException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    }
    return result;
}

From source file:org.ejbca.core.model.ca.caadmin.CmsCAServiceTest.java

License:Open Source License

@Test
public void testCmsCAServiceActive() throws Exception {

    // Activate the service first
    testActivateCmsCAService();// ww  w . j  a  v  a  2  s  .c  om

    CmsCAServiceRequest request = new CmsCAServiceRequest(doc, CmsCAServiceRequest.MODE_SIGN);
    CmsCAServiceResponse resp = null;
    // Try the request again
    boolean active = true;
    try {
        resp = (CmsCAServiceResponse) caAdminSession.extendedService(admin, getTestCAId(), request);
    } catch (ExtendedCAServiceNotActiveException e) {
        active = false;
    }
    // By default the CA service is not active
    assertTrue(active);

    assertNotNull(resp);
    byte[] respdoc = resp.getCmsDocument();
    assertNotNull(resp);
    CMSSignedData csd = new CMSSignedData(respdoc);
    SignerInformationStore infoStore = csd.getSignerInfos();
    @SuppressWarnings("unchecked")
    Collection<SignerInformation> signers = infoStore.getSigners();
    Iterator<SignerInformation> iter = signers.iterator();
    if (iter.hasNext()) {
        SignerInformation si = iter.next();
        assertNotNull(si);
        // log.info("Digest alg is: "+si.getDigestAlgOID());
        assertEquals(CMSSignedGenerator.DIGEST_SHA1, si.getDigestAlgOID());
        SignerId sid = si.getSID();
        // log.info(sid.toString());
        X500Name issuer = sid.getIssuer();
        assertNotNull(issuer);
        assertEquals("CN=TEST", issuer.toString());
    }
    Store store = csd.getCertificates();
    @SuppressWarnings("unchecked")
    Collection<X509CertificateHolder> certs = store.getMatches(null);
    assertEquals(2, certs.size());

    CMSProcessable cp = csd.getSignedContent();
    Object o = cp.getContent();
    byte[] ob = (byte[]) o;
    assertEquals(new String(doc), new String(ob));
}

From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java

License:Open Source License

private void checkScepResponse(byte[] retMsg, String userDN, String _senderNonce, String _transId,
        boolean crlRep, String digestOid, boolean noca)
        throws CMSException, OperatorCreationException, NoSuchProviderException, CRLException,
        InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException {

    // Parse response message
    ////from w  w w.  jav a 2s. c  o m
    CMSSignedData s = new CMSSignedData(retMsg);
    // The signer, i.e. the CA, check it's the right CA
    SignerInformationStore signers = s.getSignerInfos();
    @SuppressWarnings("unchecked")
    Collection<SignerInformation> col = signers.getSigners();
    assertTrue(col.size() > 0);
    Iterator<SignerInformation> iter = col.iterator();
    SignerInformation signerInfo = iter.next();
    // Check that the message is signed with the correct digest alg
    assertEquals(signerInfo.getDigestAlgOID(), digestOid);
    SignerId sinfo = signerInfo.getSID();
    // Check that the signer is the expected CA
    assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()),
            CertTools.stringToBCDNString(sinfo.getIssuer().toString()));
    // Verify the signature
    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
    JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
            calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
    boolean ret = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cacert.getPublicKey()));
    assertTrue(ret);
    // Get authenticated attributes
    AttributeTable tab = signerInfo.getSignedAttributes();
    // --Fail info
    Attribute attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo));
    // No failInfo on this success message
    assertNull(attr);
    // --Message type
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType));
    assertNotNull(attr);
    ASN1Set values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    ASN1String str = DERPrintableString.getInstance((values.getObjectAt(0)));
    String messageType = str.getString();
    assertEquals("3", messageType);
    // --Success status
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    assertEquals(ResponseStatus.SUCCESS.getStringValue(), str.getString());
    // --SenderNonce
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    assertTrue(octstr.getOctets().length == 16);
    // --Recipient Nonce
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // recipient nonce should be the same as we sent away as sender nonce
    assertEquals(_senderNonce, new String(Base64.encode(octstr.getOctets())));
    // --Transaction ID
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_transId));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    // transid should be the same as the one we sent
    assertEquals(_transId, str.getString());

    //
    // Check different message types
    //
    if (messageType.equals("3")) {
        // First we extract the encrypted data from the CMS enveloped data
        // contained
        // within the CMS signed data
        final CMSProcessable sp = s.getSignedContent();
        final byte[] content = (byte[]) sp.getContent();
        final CMSEnvelopedData ed = new CMSEnvelopedData(content);
        final RecipientInformationStore recipients = ed.getRecipientInfos();
        Store certstore;

        @SuppressWarnings("unchecked")
        Collection<RecipientInformation> c = recipients.getRecipients();
        assertEquals(c.size(), 1);
        Iterator<RecipientInformation> riIterator = c.iterator();
        byte[] decBytes = null;
        RecipientInformation recipient = riIterator.next();
        JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key1.getPrivate());
        rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
        decBytes = recipient.getContent(rec);
        // This is yet another CMS signed data
        CMSSignedData sd = new CMSSignedData(decBytes);
        // Get certificates from the signed data
        certstore = sd.getCertificates();

        if (crlRep) {
            // We got a reply with a requested CRL
            @SuppressWarnings("unchecked")
            final Collection<X509CRLHolder> crls = (Collection<X509CRLHolder>) sd.getCRLs().getMatches(null);
            assertEquals(crls.size(), 1);
            final Iterator<X509CRLHolder> it = crls.iterator();
            // CRL is first (and only)
            final X509CRL retCrl = new JcaX509CRLConverter().getCRL(it.next());
            log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName());

            // check the returned CRL
            assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retCrl));
            retCrl.verify(cacert.getPublicKey());
        } else {
            // We got a reply with a requested certificate
            @SuppressWarnings("unchecked")
            final Collection<X509CertificateHolder> certs = (Collection<X509CertificateHolder>) certstore
                    .getMatches(null);
            // EJBCA returns the issued cert and the CA cert (cisco vpn
            // client requires that the ca cert is included)
            if (noca) {
                assertEquals(certs.size(), 1);
            } else {
                assertEquals(certs.size(), 2);
            }
            final Iterator<X509CertificateHolder> it = certs.iterator();
            // Issued certificate must be first
            boolean verified = false;
            boolean gotcacert = false;
            JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
            while (it.hasNext()) {
                X509Certificate retcert = jcaX509CertificateConverter.getCertificate(it.next());
                log.info("Got cert with DN: " + retcert.getSubjectDN().getName());

                // check the returned certificate
                String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName());
                if (CertTools.stringToBCDNString(userDN).equals(subjectdn)) {
                    // issued certificate
                    assertEquals(CertTools.stringToBCDNString(userDN), subjectdn);
                    assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retcert));
                    retcert.verify(cacert.getPublicKey());
                    assertTrue(checkKeys(key1.getPrivate(), retcert.getPublicKey()));
                    verified = true;
                } else {
                    // ca certificate
                    assertEquals(CertTools.getSubjectDN(cacert), CertTools.getSubjectDN(retcert));
                    gotcacert = true;
                }
            }
            assertTrue(verified);
            if (noca) {
                assertFalse(gotcacert);
            } else {
                assertTrue(gotcacert);
            }
        }
    }

}

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

License:Open Source License

/**
 * Method used to verify signed data./*  w w  w . j a va 2 s.  c om*/
 * 
 * @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.ejbca.extra.ra.ProtocolScepHttpTest.java

License:Open Source License

private void checkScepResponse(byte[] retMsg, String senderNonce, String transId, boolean crlRep,
        String digestOid, boolean noca, ResponseStatus expectedResponseStatus)
        throws CMSException, NoSuchProviderException, NoSuchAlgorithmException, CertStoreException,
        InvalidKeyException, CertificateException, SignatureException, CRLException, IOException {
    ////from ww w.  j ava 2  s . c  om
    // Parse response message
    //
    CMSSignedData s = new CMSSignedData(retMsg);
    // The signer, i.e. the CA, check it's the right CA
    SignerInformationStore signers = s.getSignerInfos();
    Collection col = signers.getSigners();
    assertTrue(col.size() > 0);
    Iterator iter = col.iterator();
    SignerInformation signerInfo = (SignerInformation) iter.next();
    // Check that the message is signed with the correct digest alg
    assertEquals(signerInfo.getDigestAlgOID(), digestOid);
    SignerId sinfo = signerInfo.getSID();
    // Check that the signer is the expected CA
    assertEquals(CertTools.stringToBCDNString(racert.getIssuerDN().getName()),
            CertTools.stringToBCDNString(sinfo.getIssuerAsString()));
    // Verify the signature
    boolean ret = signerInfo.verify(racert.getPublicKey(), "BC");
    assertTrue(ret);
    // Get authenticated attributes
    AttributeTable tab = signerInfo.getSignedAttributes();
    // --Fail info
    Attribute attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_failInfo));
    // No failInfo on this success message
    if (expectedResponseStatus == ResponseStatus.SUCCESS) {
        assertNull(attr);
    }

    // --Message type
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_messageType));
    assertNotNull(attr);
    ASN1Set values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    DERString str = DERPrintableString.getInstance((values.getObjectAt(0)));
    String messageType = str.getString();
    assertEquals("3", messageType);
    // --Success status
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_pkiStatus));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    String responsestatus = str.getString();
    assertEquals(expectedResponseStatus.getValue(), responsestatus);
    // --SenderNonce
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_senderNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // SenderNonce is something the server came up with, but it should be 16 chars
    assertTrue(octstr.getOctets().length == 16);
    // --Recipient Nonce
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_recipientNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // recipient nonce should be the same as we sent away as sender nonce
    assertEquals(senderNonce, new String(Base64.encode(octstr.getOctets())));
    // --Transaction ID
    attr = tab.get(new DERObjectIdentifier(ScepRequestMessage.id_transId));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    // transid should be the same as the one we sent
    assertEquals(transId, str.getString());

    //
    // Check different message types
    //        
    if (!responsestatus.equals(ResponseStatus.PENDING.getValue()) && messageType.equals("3")) {
        // First we extract the encrypted data from the CMS enveloped data contained
        // within the CMS signed data
        CMSProcessable sp = s.getSignedContent();
        byte[] content = (byte[]) sp.getContent();
        CMSEnvelopedData ed = new CMSEnvelopedData(content);
        RecipientInformationStore recipients = ed.getRecipientInfos();
        Collection c = recipients.getRecipients();
        assertEquals(c.size(), 1);
        Iterator it = c.iterator();
        byte[] decBytes = null;
        RecipientInformation recipient = (RecipientInformation) it.next();
        decBytes = recipient.getContent(keys.getPrivate(), "BC");
        // This is yet another CMS signed data
        CMSSignedData sd = new CMSSignedData(decBytes);
        // Get certificates from the signed data
        CertStore certstore = sd.getCertificatesAndCRLs("Collection", "BC");
        if (crlRep) {
            // We got a reply with a requested CRL
            Collection crls = certstore.getCRLs(null);
            assertEquals(crls.size(), 1);
            it = crls.iterator();
            X509CRL retCrl = null;
            // CRL is first (and only)
            retCrl = (X509CRL) it.next();
            log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName());
            //                try {
            //                    FileOutputStream fos = new FileOutputStream("sceptest.der");
            //                    fos.write(retCrl.getEncoded());
            //                    fos.close();
            //                } catch (Exception e) {}
            // check the returned CRL
            assertEquals(cacert.getSubjectDN().getName(), retCrl.getIssuerDN().getName());
            retCrl.verify(cacert.getPublicKey());
        } else {
            // We got a reply with a requested certificate 
            Collection certs = certstore.getCertificates(null);
            log.info("Got certificate reply with certchain of length: " + certs.size());
            // EJBCA returns the issued cert and the CA cert (cisco vpn client requires that the ca cert is included)
            if (noca) {
                assertEquals(certs.size(), 1);
            } else {
                assertEquals(certs.size(), 2);
            }
            it = certs.iterator();
            // Issued certificate must be first
            boolean verified = false;
            boolean gotcacert = false;
            String mysubjectdn = CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest");
            X509Certificate usercert = null;
            while (it.hasNext()) {
                X509Certificate retcert = (X509Certificate) it.next();
                //                    try {
                //                        FileOutputStream fos = new FileOutputStream("sceptest.der");
                //                        fos.write(retcert.getEncoded());
                //                        fos.close();
                //                    } catch (Exception e) {}

                // check the returned certificate
                String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName());
                if (mysubjectdn.equals(subjectdn)) {
                    System.out.println("Got user cert with DN: " + retcert.getSubjectDN().getName());
                    // issued certificate
                    assertEquals(CertTools.stringToBCDNString("C=SE,O=PrimeKey,CN=sceptest"), subjectdn);
                    //System.out.println(retcert);
                    //System.out.println(cacert);
                    retcert.verify(cacert.getPublicKey());
                    assertTrue(checkKeys(keys.getPrivate(), retcert.getPublicKey()));
                    verified = true;
                    String altName = CertTools.getSubjectAlternativeName(retcert);
                    assertEquals("iPAddress=10.0.0.1, dNSName=foo.bar.com", altName);
                    usercert = retcert;
                } else {
                    log.info("Got CA cert with DN: " + retcert.getSubjectDN().getName());
                    // ca certificate
                    assertEquals(cacert.getSubjectDN().getName(), retcert.getSubjectDN().getName());
                    gotcacert = true;
                    usercert.verify(retcert.getPublicKey());
                }
            }
            assertTrue(verified);
            if (noca) {
                assertFalse(gotcacert);
            } else {
                assertTrue(gotcacert);
            }
        }
    }

}

From source file:org.jnotary.crypto.Verifier.java

License:Open Source License

@SuppressWarnings("rawtypes")
public VerifyResult verifySignature(byte[] signedData, TrustedStore trustedUserCertificateStore)
        throws Exception {
    CMSSignedData sdata = new CMSSignedData(signedData);
    Store certStore = sdata.getCertificates();
    SignerInformationStore signersStore = sdata.getSignerInfos();
    Collection signers = signersStore.getSigners();
    Iterator it = signers.iterator();

    final Map<SignerId, java.security.cert.X509Certificate> certificates = new HashMap<SignerId, java.security.cert.X509Certificate>();

    List<SignerInformation> signerInfoList = new ArrayList<SignerInformation>();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        signerInfoList.add(signer);//from  www. j  ava2  s .  c om
        X509CertificateHolder cert = getCertificateHolder(trustedUserCertificateStore, certStore, signer);
        ByteArrayInputStream certBais = new ByteArrayInputStream(cert.getEncoded());
        java.security.cert.X509Certificate x509cert = (java.security.cert.X509Certificate) CertificateFactory
                .getInstance("X.509").generateCertificate(certBais);
        certificates.put(signer.getSID(), x509cert);

        verifyDate(signer, x509cert);

        if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            throw new Exception("Signature verification failed for " + cert.getSubject().toString());
    }
    CMSTypedData ctd = sdata.getSignedContent();
    if (ctd == null)
        throw new Exception("Data not exists");
    return new VerifyResult((byte[]) ctd.getContent(), signerInfoList, certificates);
}

From source file:org.jnotary.dvcs.SimpleRequestTest.java

License:Open Source License

@Test(expected = Exception.class)
public void parseCpkcRFCExample() throws IOException, CMSException {

    Reader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream("ccpdReqRfc.pem"));
    PEMParser pemParser = new PEMParser(reader);
    byte[] content = pemParser.readPemObject().getContent();
    CMSSignedData signedData = new CMSSignedData(content);
    CMSTypedData data = signedData.getSignedContent();

    DVCSRequest reqIn = DVCSRequest.getInstance(data.getContent());
    assertTrue("Service type is incorrect", reqIn.getRequestInformation().getService() == ServiceType.CCPD);
}

From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java

License:Apache License

/**
 * Retrieve the signed content from a SignedData object. Signature MUST BE
 * VERIFIED apart since it's the original data without the signature
 * information./*from  w  w w. j a v a2 s  .co m*/
 * 
 * @param encoded
 *            the SignedData object
 * @return the original data from signed content
 * @throws CMSException
 */
public static byte[] parseSignedData(byte[] encoded) throws CMSException {

    installBouncyCastleProviderIfNecessary();

    CMSSignedData signed = new CMSSignedData(encoded);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        signed.getSignedContent().write(bout);
    } catch (IOException e) {
        // ignore in a hope it won't happen with ByteArrayOutputStream
        LOGGER.error("parseSignedData() - Failed to retrieve SignedData content.", e);
        return null;
    }
    byte[] content = bout.toByteArray();

    return content;
}