Example usage for org.bouncycastle.cms CMSSignedData getCertificates

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

Introduction

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

Prototype

public Store<X509CertificateHolder> getCertificates() 

Source Link

Document

Return any X.509 certificate objects in this SignedData structure as a Store of X509CertificateHolder objects.

Usage

From source file:org.roda.core.plugins.plugins.characterization.SignatureUtility.java

private boolean verifySignatures(CMSSignedData s, byte[] contentDigest)
        throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, CMSException {
    boolean valid = true;

    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 certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate cert = new JcaX509CertificateConverter().setProvider(provider)
                .getCertificate(certHolder);
        boolean certValid = signer.verify(cert, provider);
        valid &= certValid;/*from   w w w  . j a v a 2  s .c om*/

        if (!certValid) {
            LOGGER.error("Invalid certificate '{}'", cert);
        }

        if (contentDigest != null) {
            boolean digestValid = MessageDigest.isEqual(contentDigest, signer.getContentDigest());
            valid &= digestValid;

            if (!digestValid) {
                LOGGER.error("Invalid digest '{}'", contentDigest);
            }
        }
    }

    return valid;
}

From source file:org.signserver.module.renewal.worker.RenewalWorker.java

License:Open Source License

private void renewWorker(final int workerId, final String sigAlg, final String subjectDN,
        final String endEntity, final boolean explicitEccParameters, final boolean defaultKey,
        final String nextCertSignKey, final LogMap logMap) throws Exception {

    final String pkcs10 = createRequestPEM(workerId, sigAlg, subjectDN, explicitEccParameters, defaultKey);

    if (LOG.isDebugEnabled()) {
        LOG.debug("PKCS10: " + pkcs10);
    }//from   w  w  w  .  ja  v  a  2  s.co  m

    // Connect to EjbcaWS
    final EjbcaWS ejbcaws = getEjbcaWS(ejbcaWsUrl, alias, truststoreType, truststorePath, truststoreValue,
            truststorePass);

    if (ejbcaws == null) {
        LOG.debug("Could not get EjbcaWS");
    } else {
        LOG.debug("Got EjbcaWS");

        final UserMatch usermatch = new UserMatch();
        usermatch.setMatchwith(MATCH_WITH_USERNAME);
        usermatch.setMatchtype(MATCH_TYPE_EQUALS);
        usermatch.setMatchvalue(endEntity);
        final List<UserDataVOWS> result = ejbcaws.findUser(usermatch);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Got users: " + result);
        }
        if (result.isEmpty()) {
            throw new IllegalArgumentException("End entity not found in EJBCA: " + endEntity);
        } else {
            // Update user with status and new password
            final UserDataVOWS user1 = result.get(0);
            final char[] password = RandomPasswordGenerator.getInstance().generate(20);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Changing to status to NEW from " + user1.getStatus() + " for end entity " + endEntity
                        + ".");
            }
            user1.setStatus(STATUS_NEW);
            user1.setPassword(new String(password));
            ejbcaws.editUser(user1);

            // Send request to CA
            final CertificateResponse resp = ejbcaws.pkcs10Request(endEntity, new String(password), pkcs10,
                    null, RESPONSETYPE_PKCS7WITHCHAIN);

            RandomPasswordGenerator.getInstance().fill(password);

            final String b64Cert = new String(resp.getData());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Got PKCS7: " + b64Cert);
            }

            final CMSSignedData signedData = new CMSSignedData(Base64.decode(b64Cert));

            final Store certStore = signedData.getCertificates();
            final List<X509CertificateHolder> certChain = getCertificateChain(
                    certStore.getMatches(new RenewalWorker.AllSelector()));
            if (LOG.isDebugEnabled()) {
                LOG.debug("Got certificates: " + certChain);
            }

            final X509CertificateHolder signerCert = getEndEntityCertificate(certChain);
            if (LOG.isDebugEnabled()) {
                LOG.debug("New certificate subject DN: " + signerCert.getSubject());
            }

            // Log
            logMap.put(RenewalWorkerProperties.LOG_NEWCERTISSUERDN, signerCert.getIssuer().toString());
            logMap.put(RenewalWorkerProperties.LOG_NEWCERTSERIALNO, signerCert.getSerialNumber().toString(16));
            logMap.put(RenewalWorkerProperties.LOG_NEWCERTSUBJECTDN, signerCert.getSubject().toString());

            // TODO: Check the certificate
            // Public key should match

            // Update worker to use the new certificate
            getWorkerSession().uploadSignerCertificate(workerId, signerCert.getEncoded(),
                    GlobalConfiguration.SCOPE_GLOBAL);
            getWorkerSession().uploadSignerCertificateChain(workerId, getCertificateChainBytes(certChain),
                    GlobalConfiguration.SCOPE_GLOBAL);

            // If not the default key we need to promote the key
            // Set DEFAULTKEY to NEXTCERTSIGNKEY
            if (defaultKey) {
                LOG.debug("Uploaded was for DEFAULTKEY");
            } else if (!defaultKey && nextCertSignKey != null) {
                LOG.debug("Uploaded was for NEXTCERTSIGNKEY");

                getWorkerSession().setWorkerProperty(workerId, "DEFAULTKEY", nextCertSignKey);
                getWorkerSession().removeWorkerProperty(workerId, NEXTCERTSIGNKEY);
            }

            getWorkerSession().reloadConfiguration(workerId);
            LOG.debug("New configuration applied");
        }
    }
}

From source file:org.signserver.server.cryptotokens.P11SignTest.java

License:Open Source License

private void msauthTSSigner(final int workerId) throws Exception {
    // Generate CSR
    PKCS10CertReqInfo certReqInfo = new PKCS10CertReqInfo("SHA1WithRSA", "CN=Worker" + workerId, null);
    Base64SignerCertReqData reqData = (Base64SignerCertReqData) getWorkerSession()
            .getCertificateRequest(workerId, certReqInfo, false);

    // Issue certificate
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Base64.decode(reqData.getBase64CertReq()));
    KeyPair issuerKeyPair = CryptoUtils.generateRSA(512);
    X509CertificateHolder cert = new X509v3CertificateBuilder(new X500Name("CN=TestP11 Issuer"), BigInteger.ONE,
            new Date(), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365)), csr.getSubject(),
            csr.getSubjectPublicKeyInfo())
                    .addExtension(org.bouncycastle.asn1.x509.X509Extension.extendedKeyUsage, true,
                            new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping))
                    .build(new JcaContentSignerBuilder("SHA256WithRSA").setProvider("BC")
                            .build(issuerKeyPair.getPrivate()));

    // Install certificate and chain
    workerSession.uploadSignerCertificate(workerId, cert.getEncoded(), GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.uploadSignerCertificateChain(workerId, Arrays.asList(cert.getEncoded()),
            GlobalConfiguration.SCOPE_GLOBAL);
    workerSession.reloadConfiguration(workerId);

    // Test active
    List<String> errors = workerSession.getStatus(workerId).getFatalErrors();
    assertEquals("errors: " + errors, 0, errors.size());

    // Test signing
    GenericSignRequest signRequest = new GenericSignRequest(678, MSAUTHCODE_REQUEST_DATA.getBytes());
    final GenericSignResponse res = (GenericSignResponse) workerSession.process(workerId, signRequest,
            new RequestContext());
    Certificate signercert = res.getSignerCertificate();
    assertNotNull(signercert);/*from   w ww.  j a v a  2s . c om*/

    byte[] buf = res.getProcessedData();
    CMSSignedData s = new CMSSignedData(Base64.decode(buf));

    int verified = 0;
    Store certStore = s.getCertificates();
    SignerInformationStore signers = s.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certStore.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder signerCert = (X509CertificateHolder) certIt.next();

        if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(signerCert))) {
            verified++;
        }
    }

    assertEquals("signer verified", 1, verified);
}

From source file:org.votingsystem.signature.smime.SMIMEMessage.java

License:Open Source License

private void replaceSigners(CMSSignedData cmsdata) throws Exception {
    log.info("replaceSigners");
    SMIMESignedGenerator gen = new SMIMESignedGenerator();
    gen.addAttributeCertificates(cmsdata.getAttributeCertificates());
    gen.addCertificates(cmsdata.getCertificates());
    gen.addSigners(cmsdata.getSignerInfos());
    MimeMultipart mimeMultipart = gen.generate(smimeSigned.getContent(),
            smimeSigned.getContent().getFileName());
    setContent(mimeMultipart, mimeMultipart.getContentType());
    saveChanges();// w  w  w  . java 2  s. c  o  m
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

License:Open Source License

public byte[] getPKIMessage(InputStream inputStream) throws KeystoreException {

    try {//from w  w  w.  ja  va2 s  .c  om
        CMSSignedData signedData = new CMSSignedData(inputStream);
        Store reqStore = signedData.getCertificates();
        @SuppressWarnings("unchecked")
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        KeyStoreReader keyStoreReader = new KeyStoreReader();
        PrivateKey privateKeyRA = keyStoreReader.getRAPrivateKey();
        PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
        X509Certificate certRA = (X509Certificate) keyStoreReader.getRACertificate();
        X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();

        CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509);
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream);

        PkcsPkiEnvelopeDecoder envelopeDecoder = new PkcsPkiEnvelopeDecoder(certRA, privateKeyRA);
        PkiMessageDecoder messageDecoder = new PkiMessageDecoder(reqCert, envelopeDecoder);
        PkiMessage<?> pkiMessage = messageDecoder.decode(signedData);
        Object msgData = pkiMessage.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = pkiMessage.getTransactionId();
        Nonce recipientNonce = pkiMessage.getSenderNonce();
        CertRep certRep;

        PKCS10CertificationRequest certRequest = (PKCS10CertificationRequest) msgData;
        X509Certificate generatedCert = generateCertificateFromCSR(
                privateKeyCA, certRequest, certCA.getIssuerX500Principal().getName());

        List<X509Certificate> issued = new ArrayList<X509Certificate>();
        issued.add(generatedCert);

        if (issued.size() == 0) {
            certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
        } else {
            CMSSignedData messageData = getMessageData(issued);
            certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, CertificateManagementConstants.DES_EDE);
        PkiMessageEncoder encoder = new PkiMessageEncoder(privateKeyRA, certRA, envEncoder);
        CMSSignedData cmsSignedData = encoder.encode(certRep);

        return cmsSignedData.getEncoded();

    } catch (CertificateException e) {
        String errorMsg = "Certificate issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (MessageEncodingException e) {
        String errorMsg = "Message encoding issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Input output issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (MessageDecodingException e) {
        String errorMsg = "Message decoding issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    } catch (CMSException e) {
        String errorMsg = "CMS issue occurred when generating getPKIMessage";
        throw new KeystoreException(errorMsg, e);
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

License:Open Source License

public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException {

    if (headerSignature == null || headerSignature.isEmpty()) {
        return null;
    }/*from   w ww . j  a  va  2s . co m*/

    try {
        KeyStoreReader keyStoreReader = new KeyStoreReader();
        CMSSignedData signedData = new CMSSignedData(Base64.decodeBase64(headerSignature.getBytes()));
        Store reqStore = signedData.getCertificates();
        @SuppressWarnings("unchecked")
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        if (reqCerts != null && reqCerts.size() > 0) {
            CertificateFactory certificateFactory = CertificateFactory.getInstance(CertificateManagementConstants.X_509);
            X509CertificateHolder holder = reqCerts.iterator().next();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded());
            X509Certificate reqCert = (X509Certificate) certificateFactory.
                    generateCertificate(byteArrayInputStream);

            if (reqCert != null && reqCert.getSerialNumber() != null) {
                Certificate lookUpCertificate = keyStoreReader.getCertificateByAlias(
                        reqCert.getSerialNumber().toString());

                if (lookUpCertificate instanceof X509Certificate) {
                    return (X509Certificate) lookUpCertificate;
                }
            }

        }
    } catch (CMSException e) {
        String errorMsg = "CMSException when decoding certificate signature";
        throw new KeystoreException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "IOException when decoding certificate signature";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "CertificateException when decoding certificate signature";
        throw new KeystoreException(errorMsg, e);
    }

    return null;
}

From source file:org.wso2.carbon.identity.certificateauthority.endpoint.scep.ScepEndpoint.java

License:Open Source License

private Response pkiOperation(int tenantId, HttpServletRequest request) {
    try {//  ww w .  j  ava 2 s .c o m
        byte[] body = getMessageBytes(request);
        CMSSignedData sd = new CMSSignedData(body);

        Store reqStore = sd.getCertificates();
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert = (X509Certificate) factory.generateCertificate(bais);

        PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(tenantId),
                getRecipientKey(tenantId));
        PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder);
        PkiMessage<?> msg = decoder.decode(sd);
        MessageType msgType = msg.getMessageType();
        Object msgData = msg.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = msg.getTransactionId();
        Nonce recipientNonce = msg.getSenderNonce();
        CertRep certRep;

        if (msgType == MessageType.GET_CERT) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X509Name principal = iasn.getName();
            final BigInteger serial = iasn.getSerialNumber().getValue();
            List<X509Certificate> issued = doGetCert(principal, serial);
            if (issued.size() == 0) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
            } else {
                CMSSignedData messageData = getMessageData(issued);

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            }
        } else if (msgType == MessageType.GET_CERT_INITIAL) {
            final IssuerAndSubject ias = (IssuerAndSubject) msgData;
            final X500Name issuer = X500Name.getInstance(ias.getIssuer());
            final X500Name subject = X500Name.getInstance(ias.getSubject());

            try {
                List<X509Certificate> issued = doGetCertInitial(tenantId, issuer, subject, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CRL) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X509Name issuer = iasn.getName();
            final BigInteger serialNumber = iasn.getSerialNumber().getValue();

            try {
                CMSSignedData messageData = getMessageData(doGetCrl(tenantId, issuer, serialNumber));

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.PKCS_REQ) {
            final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData;

            try {
                List<X509Certificate> issued = doEnrol(certReq, transId, tenantId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else {
            log.error("Unknown message for operation");
            return ResponseUtils.badRequest("Unknown message for operation");
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede");
        PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(tenantId), getSigner(tenantId),
                envEncoder);
        CMSSignedData signedData = encoder.encode(certRep);

        return Response.ok().type("application/x-pki-message").entity(signedData.getEncoded()).build();
    } catch (Exception e) {
        log.error(e);
        return ResponseUtils.serverError();
    }
}

From source file:org.xipki.pki.scep.message.DecodedNextCaMessage.java

License:Open Source License

@SuppressWarnings("unchecked")
public static DecodedNextCaMessage decode(final CMSSignedData pkiMessage,
        final CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
    ParamUtil.requireNonNull("pkiMessage", pkiMessage);

    SignerInformationStore signerStore = pkiMessage.getSignerInfos();
    Collection<SignerInformation> signerInfos = signerStore.getSigners();
    if (signerInfos.size() != 1) {
        throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
    }//from w  w w. j a  v a2 s.c om

    SignerInformation signerInfo = signerInfos.iterator().next();

    SignerId sid = signerInfo.getSID();

    Collection<?> signedDataCerts = null;
    if (certStore != null) {
        signedDataCerts = certStore.getMatches(sid);
    }

    if (signedDataCerts == null || signedDataCerts.isEmpty()) {
        signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
    }

    if (signedDataCerts == null || signedDataCerts.size() != 1) {
        throw new MessageDecodingException("could not find embedded certificate to verify the signature");
    }

    AttributeTable signedAttrs = signerInfo.getSignedAttributes();
    if (signedAttrs == null) {
        throw new MessageDecodingException("missing signed attributes");
    }

    Date signingTime = null;
    // signingTime
    ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
    if (attrValue != null) {
        signingTime = Time.getInstance(attrValue).getDate();
    }

    DecodedNextCaMessage ret = new DecodedNextCaMessage();
    if (signingTime != null) {
        ret.setSigningTime(signingTime);
    }

    ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm();
    ret.setDigestAlgorithm(digestAlgOid);

    String sigAlgOid = signerInfo.getEncryptionAlgOID();
    if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
        ASN1ObjectIdentifier tmpDigestAlgOid;
        try {
            tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(),
                    signerInfo.getEncryptionAlgParams());
        } catch (Exception ex) {
            final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: "
                    + ex.getMessage();
            LOG.error(msg);
            LOG.debug(msg, ex);
            ret.setFailureMessage(msg);
            return ret;
        }
        if (!digestAlgOid.equals(tmpDigestAlgOid)) {
            ret.setFailureMessage(
                    "digestAlgorithm and encryptionAlgorithm do not use" + " the same digestAlgorithm");
            return ret;
        }
    } // end if

    X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
    X509Certificate signerCert;
    try {
        signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure());
    } catch (CertificateException ex) {
        final String msg = "could not construct X509CertificateObject: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setSignatureCert(signerCert);

    // validate the signature
    SignerInformationVerifier verifier;
    try {
        verifier = new JcaSimpleSignerInfoVerifierBuilder().build(signerCert.getPublicKey());
    } catch (OperatorCreationException ex) {
        final String msg = "could not build signature verifier: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    boolean signatureValid;
    try {
        signatureValid = signerInfo.verify(verifier);
    } catch (CMSException ex) {
        final String msg = "could not verify the signature: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    ret.setSignatureValid(signatureValid);
    if (!signatureValid) {
        return ret;
    }

    // MessageData
    CMSTypedData signedContent = pkiMessage.getSignedContent();
    ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
    if (!CMSObjectIdentifiers.signedData.equals(signedContentType)) {
        // fall back: some SCEP client use id-data
        if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
            ret.setFailureMessage(
                    "either id-signedData or id-data is excepted, but not '" + signedContentType.getId());
            return ret;
        }
    }

    ContentInfo contentInfo = ContentInfo.getInstance((byte[]) signedContent.getContent());
    SignedData signedData = SignedData.getInstance(contentInfo.getContent());

    List<X509Certificate> certs;
    try {
        certs = ScepUtil.getCertsFromSignedData(signedData);
    } catch (CertificateException ex) {
        final String msg = "could not extract Certificates from the message: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    final int n = certs.size();

    X509Certificate caCert = null;
    List<X509Certificate> raCerts = new LinkedList<X509Certificate>();
    for (int i = 0; i < n; i++) {
        X509Certificate cert = certs.get(i);
        if (cert.getBasicConstraints() > -1) {
            if (caCert != null) {
                final String msg = "multiple CA certificates is returned, but exactly 1 is expected";
                LOG.error(msg);
                ret.setFailureMessage(msg);
                return ret;
            }
            caCert = cert;
        } else {
            raCerts.add(cert);
        }
    } // end for

    if (caCert == null) {
        final String msg = "no CA certificate is returned";
        LOG.error(msg);
        ret.setFailureMessage(msg);
        return ret;
    }

    X509Certificate[] locaRaCerts;
    if (raCerts.isEmpty()) {
        locaRaCerts = null;
    } else {
        locaRaCerts = raCerts.toArray(new X509Certificate[0]);
    }

    AuthorityCertStore authorityCertStore = AuthorityCertStore.getInstance(caCert, locaRaCerts);
    ret.setAuthorityCertStore(authorityCertStore);

    return ret;
}

From source file:org.xipki.pki.scep.message.DecodedPkiMessage.java

License:Open Source License

@SuppressWarnings("unchecked")
public static DecodedPkiMessage decode(final CMSSignedData pkiMessage, final EnvelopedDataDecryptor recipient,
        final CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
    ParamUtil.requireNonNull("pkiMessage", pkiMessage);
    ParamUtil.requireNonNull("recipient", recipient);

    SignerInformationStore signerStore = pkiMessage.getSignerInfos();
    Collection<SignerInformation> signerInfos = signerStore.getSigners();
    if (signerInfos.size() != 1) {
        throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
    }//from   ww w  . ja va2 s  . c o  m

    SignerInformation signerInfo = signerInfos.iterator().next();
    SignerId sid = signerInfo.getSID();

    Collection<?> signedDataCerts = null;
    if (certStore != null) {
        signedDataCerts = certStore.getMatches(sid);
    }

    if (signedDataCerts == null || signedDataCerts.isEmpty()) {
        signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
    }

    if (signedDataCerts == null || signedDataCerts.size() != 1) {
        throw new MessageDecodingException("could not find embedded certificate to verify the signature");
    }

    AttributeTable signedAttrs = signerInfo.getSignedAttributes();
    if (signedAttrs == null) {
        throw new MessageDecodingException("missing SCEP attributes");
    }

    Date signingTime = null;
    // signingTime
    ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
    if (attrValue != null) {
        signingTime = Time.getInstance(attrValue).getDate();
    }

    // transactionId
    String str = getPrintableStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_TRANSACTION_ID);
    if (str == null || str.isEmpty()) {
        throw new MessageDecodingException("missing required SCEP attribute transactionId");
    }
    TransactionId transactionId = new TransactionId(str);

    // messageType
    Integer intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_MESSAGE_TYPE);
    if (intValue == null) {
        throw new MessageDecodingException(
                "tid " + transactionId.getId() + ": missing required SCEP attribute messageType");
    }

    MessageType messageType;
    try {
        messageType = MessageType.forValue(intValue);
    } catch (IllegalArgumentException ex) {
        throw new MessageDecodingException(
                "tid " + transactionId.getId() + ": invalid messageType '" + intValue + "'");
    }

    // senderNonce
    Nonce senderNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SENDER_NONCE);
    if (senderNonce == null) {
        throw new MessageDecodingException(
                "tid " + transactionId.getId() + ": missing required SCEP attribute senderNonce");
    }

    DecodedPkiMessage ret = new DecodedPkiMessage(transactionId, messageType, senderNonce);
    if (signingTime != null) {
        ret.setSigningTime(signingTime);
    }

    Nonce recipientNonce = null;
    try {
        recipientNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_RECIPIENT_NONCE);
    } catch (MessageDecodingException ex) {
        ret.setFailureMessage("could not parse recipientNonce: " + ex.getMessage());
    }

    if (recipientNonce != null) {
        ret.setRecipientNonce(recipientNonce);
    }

    PkiStatus pkiStatus = null;
    FailInfo failInfo = null;
    if (MessageType.CertRep == messageType) {
        // pkiStatus
        try {
            intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_PKI_STATUS);
        } catch (MessageDecodingException ex) {
            ret.setFailureMessage("could not parse pkiStatus: " + ex.getMessage());
            return ret;
        }

        if (intValue == null) {
            ret.setFailureMessage("missing required SCEP attribute pkiStatus");
            return ret;
        }

        try {
            pkiStatus = PkiStatus.forValue(intValue);
        } catch (IllegalArgumentException ex) {
            ret.setFailureMessage("invalid pkiStatus '" + intValue + "'");
            return ret;
        }
        ret.setPkiStatus(pkiStatus);

        // failureInfo
        if (pkiStatus == PkiStatus.FAILURE) {
            try {
                intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_FAILINFO);
            } catch (MessageDecodingException ex) {
                ret.setFailureMessage("could not parse failInfo: " + ex.getMessage());
                return ret;
            }

            if (intValue == null) {
                ret.setFailureMessage("missing required SCEP attribute failInfo");
                return ret;
            }

            try {
                failInfo = FailInfo.forValue(intValue);
            } catch (IllegalArgumentException ex) {
                ret.setFailureMessage("invalid failInfo '" + intValue + "'");
                return ret;
            }

            ret.setFailInfo(failInfo);
        } // end if(pkiStatus == PkiStatus.FAILURE)
    } // end if (MessageType.CertRep == messageType)

    // other signedAttributes
    Attribute[] attrs = signedAttrs.toASN1Structure().getAttributes();
    for (Attribute attr : attrs) {
        ASN1ObjectIdentifier type = attr.getAttrType();
        if (!SCEP_ATTR_TYPES.contains(type)) {
            ret.addSignendAttribute(type, attr.getAttrValues().getObjectAt(0));
        }
    }

    // unsignedAttributes
    AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes();
    attrs = (unsignedAttrs == null) ? null : unsignedAttrs.toASN1Structure().getAttributes();
    if (attrs != null) {
        for (Attribute attr : attrs) {
            ASN1ObjectIdentifier type = attr.getAttrType();
            ret.addUnsignendAttribute(type, attr.getAttrValues().getObjectAt(0));
        }
    }

    ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm();
    ret.setDigestAlgorithm(digestAlgOid);

    String sigAlgOid = signerInfo.getEncryptionAlgOID();
    if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
        ASN1ObjectIdentifier tmpDigestAlgOid;
        try {
            tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(),
                    signerInfo.getEncryptionAlgParams());
        } catch (Exception ex) {
            final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: "
                    + ex.getMessage();
            LOG.error(msg);
            LOG.debug(msg, ex);
            ret.setFailureMessage(msg);
            return ret;
        }
        if (!digestAlgOid.equals(tmpDigestAlgOid)) {
            ret.setFailureMessage(
                    "digestAlgorithm and encryptionAlgorithm do not use the" + " same digestAlgorithm");
            return ret;
        } // end if
    } // end if

    X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
    X509Certificate signerCert;
    try {
        signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure());
    } catch (CertificateException ex) {
        final String msg = "could not construct X509Certificate: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setSignatureCert(signerCert);

    // validate the signature
    SignerInformationVerifier verifier;
    try {
        verifier = new JcaSimpleSignerInfoVerifierBuilder().build(signerCert.getPublicKey());
    } catch (OperatorCreationException ex) {
        final String msg = "could not build signature verifier: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    boolean signatureValid;
    try {
        signatureValid = signerInfo.verify(verifier);
    } catch (CMSException ex) {
        final String msg = "could not verify the signature: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    ret.setSignatureValid(signatureValid);
    if (!signatureValid) {
        return ret;
    }

    if (MessageType.CertRep == messageType
            && (pkiStatus == PkiStatus.FAILURE | pkiStatus == PkiStatus.PENDING)) {
        return ret;
    }

    // MessageData
    CMSTypedData signedContent = pkiMessage.getSignedContent();
    ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
    if (!CMSObjectIdentifiers.envelopedData.equals(signedContentType)) {
        // fall back: some SCEP client, such as JSCEP use id-data
        if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
            ret.setFailureMessage(
                    "either id-envelopedData or id-data is excepted, but not '" + signedContentType.getId());
            return ret;
        }
    }

    CMSEnvelopedData envData;
    try {
        envData = new CMSEnvelopedData((byte[]) signedContent.getContent());
    } catch (CMSException ex) {
        final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    ret.setContentEncryptionAlgorithm(envData.getContentEncryptionAlgorithm().getAlgorithm());
    byte[] encodedMessageData;
    try {
        encodedMessageData = recipient.decrypt(envData);
    } catch (MessageDecodingException ex) {
        final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);

        ret.setDecryptionSuccessful(false);
        return ret;
    }

    ret.setDecryptionSuccessful(true);

    try {
        if (MessageType.PKCSReq == messageType || MessageType.RenewalReq == messageType
                || MessageType.UpdateReq == messageType) {
            CertificationRequest messageData = CertificationRequest.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
        } else if (MessageType.CertPoll == messageType) {
            IssuerAndSubject messageData = IssuerAndSubject.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
        } else if (MessageType.GetCert == messageType || MessageType.GetCRL == messageType) {
            IssuerAndSerialNumber messageData = IssuerAndSerialNumber.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
            ret.setMessageData(messageData);
        } else if (MessageType.CertRep == messageType) {
            ContentInfo ci = ContentInfo.getInstance(encodedMessageData);
            ret.setMessageData(ci);
        } else {
            throw new RuntimeException("should not reach here, unknown messageType " + messageType);
        }
    } catch (Exception ex) {
        final String msg = "could not parse the messageData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    return ret;
}

From source file:org.xwiki.crypto.signer.internal.cms.BcCMSUtils.java

License:Open Source License

/**
 * Create a new {@link org.xwiki.crypto.signer.param.CMSSignedDataVerified} for the given signed data.
 *
 * The verified data is filled with the signed data content, content type, and certificates.
 *
 * @param signedData the signed data about to be verified.
 * @param factory a certificate factory to be used for certificates conversion.
 * @return a new verified signed data to be completed with the signature verifications.
 *//* w  w w . j a  v  a2  s. c o  m*/
public static BcCMSSignedDataVerified getCMSSignedDataVerified(CMSSignedData signedData,
        CertificateFactory factory) {
    BcCMSSignedDataVerified verifiedData = new BcCMSSignedDataVerified(signedData.getSignedContentTypeOID(),
            (signedData.getSignedContent() != null ? (byte[]) signedData.getSignedContent().getContent()
                    : null));

    BcStoreUtils.addCertificatesToVerifiedData(signedData.getCertificates(), verifiedData, factory);
    return verifiedData;
}