Example usage for org.bouncycastle.cms CMSSignedData CMSSignedData

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

Introduction

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

Prototype

public CMSSignedData(ContentInfo sigData) throws CMSException 

Source Link

Usage

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

License:Open Source License

@Override
public List<Timestamp> checkTimeStampOnSignature(byte[] signature) {
    try {/*  w  w  w.ja va2 s .  co  m*/
        Security.addProvider(new BouncyCastleProvider());
        List<Timestamp> listOfTimeStamp = new ArrayList<Timestamp>();
        CMSSignedData cmsSignedData = new CMSSignedData(signature);
        SignerInformationStore signers = cmsSignedData.getSignerInfos();
        Iterator<?> it = signers.getSigners().iterator();
        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
            Attribute attributeTimeStamp = unsignedAttributes
                    .get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
            if (attributeTimeStamp != null) {
                TimeStampOperator timeStampOperator = new TimeStampOperator();
                byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive()
                        .getEncoded();
                TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
                Timestamp timeStampSigner = new Timestamp(timeStampToken);
                timeStampOperator.validate(signer.getSignature(), varTimeStamp, null);
                listOfTimeStamp.add(timeStampSigner);
            }
        }
        return listOfTimeStamp;
    } catch (CertificateCoreException | IOException | TSPException | CMSException e) {
        throw new SignerException(e);
    }
}

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

License:Open Source License

private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content, byte[] hash) {
    try {/*from   w w w  .  ja v  a2 s  .  c  o m*/
        Security.addProvider(new BouncyCastleProvider());
        ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
        ASN1Sequence seq = (ASN1Sequence) ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier) seq.getObjectAt(0),
                (ASN1Set) seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null) {
            timeStampOperator.validate(content, varTimeStamp, null);
        } else {
            timeStampOperator.validate(null, varTimeStamp, hash);
        }
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
        Timestamp timeStampSigner = new Timestamp(timeStampToken);
        return timeStampSigner;
    } catch (CertificateCoreException | IOException | TSPException | CMSException e) {
        throw new SignerException(e);
    }

}

From source file:org.demoiselle.signer.timestamp.connector.TimeStampOperator.java

License:Open Source License

/**
 * Validate a time stamp/*from  w w  w .j  a  v a  2s . co  m*/
 *
 * @param content if it is assigned, the parameter hash must to be null
 * @param timeStamp timestamp to be validated
 * @param hash if it is assigned, the parameter content must to be null
 * @throws CertificateCoreException validate exception
 */
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
        CMSSignedData s = timeStampToken.toCMSSignedData();

        int verified = 0;

        Store<?> certStore = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();

        while (it.hasNext()) {
            SignerInformation signer = it.next();
            Collection<?> certCollection = certStore.getMatches(signer.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
            SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
                    .build(cert);
            if (signer.verify(siv)) {
                verified++;
            }
            cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
            timeStampToken.validate(siv);
        }

        logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified));

        //Valida o hash  incluso no carimbo de tempo com hash do arquivo carimbado
        byte[] calculatedHash = null;
        if (content != null) {
            Digest digest = DigestFactory.getInstance().factoryDefault();
            TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
            ASN1ObjectIdentifier algOID = info.getMessageImprintAlgOID();
            digest.setAlgorithm(algOID.toString());
            calculatedHash = digest.digest(content);
        } else {
            calculatedHash = hash;
        }

        if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
        } else {
            throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
        }

    } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
        throw new CertificateCoreException(ex.getMessage());
    }
}

From source file:org.digidoc4j.impl.bdoc.xades.TimestampSignature.java

License:GNU General Public License

private TimeStampToken createTimeStampToken(final String base64EncodedTimestamp) throws DSSException {
    logger.debug("Creating timestamp token");
    try {//from w w  w  .j a  v a  2 s .  c o  m
        byte[] tokenBytes = Base64.decodeBase64(base64EncodedTimestamp);
        CMSSignedData signedData = new CMSSignedData(tokenBytes);
        return new TimeStampToken(signedData);
    } catch (Exception e) {
        logger.error("Error parsing timestamp token: " + e.getMessage());
        throw new TechnicalException("Error parsing timestamp token", e);
    }
}

From source file:org.dihedron.crypto.operations.verify.pkcs7.PKCS7Verifier.java

License:Open Source License

/**
 * @see org.dihedron.crypto.operations.verify.Verifier#verify(byte[])
 *//*ww  w.  java  2s.c o  m*/
@Override
public boolean verify(byte[] signed) throws CryptoException {
    try {
        return verify(new CMSSignedData(signed), null);
    } catch (CMSException e) {
        logger.error("error creating CMSSignedData object", e);
        throw new CryptoException("Error creating CMSSignedData object", e);
    }
}

From source file:org.dihedron.crypto.operations.verify.pkcs7.PKCS7Verifier.java

License:Open Source License

/**
 * @see org.dihedron.crypto.operations.verify.Verifier#verify(byte[], byte[])
 *///from   w  w w. ja  v a 2 s  .  c o m
@Override
public boolean verify(byte[] signed, byte[] data) throws CryptoException {
    try {
        return verify(new CMSSignedData(signed), data);
    } catch (CMSException e) {
        logger.error("error creating CMSSignedData object", e);
        throw new CryptoException("Error creating CMSSignedData object", e);
    }
}

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

License:Open Source License

private void addRequest(final InputStream inStream, final File inFile) throws CertificateException {

    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    BufferedInputStream in = null;
    try {/*from  ww w. j  a v  a2 s . c  o  m*/
        in = new BufferedInputStream(inStream);
        int b;
        while ((b = in.read()) != -1) {
            bout.write(b);
        }
        final byte[] bytes = bout.toByteArray();

        CMSSignedData signedData = null;
        try {
            signedData = new CMSSignedData(bytes);
        } catch (Exception ex) {
            LOG.debug("Not parsed as CMS: " + ex.getMessage());
        }

        final byte[] requestBytes;
        final Request request = new Request();

        if (signedData == null) {
            requestBytes = bytes;
        } else {
            final CMSValidationResult result = validateCMS(signedData, getTrustedCerts());
            requestBytes = result.getContent();
            request.setSignerChain(result.getSignerChain());
        }

        // Parse PKCS10 and fill in requested DN
        PKCS10CertificationRequest pkcs10 = getPkcs10Request(requestBytes);
        request.setRequestedDN(pkcs10.getSubject().toString());

        request.setInFile(inFile);
        request.setOutFile(new File(inFile.getParentFile(), suggestOutFile(inFile.getName())));
        request.setRequestBytes(requestBytes);

        // Try to match beginning of filename with a user
        for (UserDataVOWS user : endEntities) {
            if (inFile.getName().toLowerCase(Locale.ENGLISH)
                    .contains(user.getUsername().toLowerCase(Locale.ENGLISH))) {
                request.setEndEntity(findEndEntity(user.getUsername()));
                break;
            }
        }

        requests.add(request);
        jTable1.revalidate();
        jTable1Changed(new TableModelEvent(jTable1.getModel(), requests.size() - 1, requests.size() - 1,
                TableModelEvent.ALL_COLUMNS, TableModelEvent.INSERT));

    } catch (IOException ex) {
        JOptionPane.showMessageDialog(getFrame(), "Problem reading file:\n" + ex.getMessage(), "Add request",
                JOptionPane.ERROR_MESSAGE);
    } catch (IllegalArgumentException ex) {
        JOptionPane.showMessageDialog(getFrame(), "Problem parsing request:\n" + ex.getMessage(), "Add request",
                JOptionPane.ERROR_MESSAGE);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                LOG.error("Error closing input file", ex);
            }
        }
    }
}

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();/*from w  ww  .  j  a va 2s  .c o  m*/

    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  ww w  .  ja v a2 s.  c om*/
    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.core.protocol.scep.ScepRequestMessage.java

License:Open Source License

/**
 * This method verifies the signature of the PKCS#7 wrapper of this message. 
 * /*from   w  w w  .j a v  a 2s  . com*/
 * @param publicKey the public key of the keypair that signed this message
 * @return true if signature verifies. 
 * @throws CMSException if the underlying byte array of this SCEP message couldn't be read
 * @throws OperatorCreationException if a signature verifier couldn't be constructed from the given public key
 */
public boolean verifySignature(PublicKey publicKey) throws CMSException, OperatorCreationException {
    CMSSignedData cmsSignedData = new CMSSignedData(scepmsg);
    return cmsSignedData.verifySignatures(new ScepVerifierProvider(publicKey));
}