Example usage for org.bouncycastle.cms SignerInformation getSignedAttributes

List of usage examples for org.bouncycastle.cms SignerInformation getSignedAttributes

Introduction

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

Prototype

public AttributeTable getSignedAttributes() 

Source Link

Document

return a table of the signed attributes - indexed by the OID of the attribute.

Usage

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

License:Open Source License

private void verify(TrustedStore trustedUserCertificateStore) throws Exception {

    File file = new File("/tmp/s1.dat");
    byte[] signedData = new byte[(int) file.length()];
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    dis.readFully(signedData);/*from   w  w  w. jav  a2s  .c  o m*/
    dis.close();

    Verifier verifier = new Verifier();
    VerifyResult result = verifier.verifySignature(signedData, trustedUserCertificateStore);
    assertTrue("Data is incorrect", Arrays.equals(result.getContent(), "Hello world!!".getBytes()));
    for (SignerInformation signerInfo : result.getSigners()) {
        final Attribute attribute = (Attribute) signerInfo.getSignedAttributes()
                .getAll(CMSAttributes.signingTime).get(0);
        final Date date = Time.getInstance(attribute.getAttrValues().getObjectAt(0)).getDate();

        System.out.println(date.toString() + " " + signerInfo.getSID());
    }

}

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

License:Open Source License

private void verifyDate(SignerInformation signer, java.security.cert.X509Certificate cert) throws Exception {
    final Attribute attribute = (Attribute) signer.getSignedAttributes().getAll(CMSAttributes.signingTime)
            .get(0);/*from w ww  .  ja  va  2  s  .  com*/
    Date date = null;
    if (attribute != null)
        date = Time.getInstance(attribute.getAttrValues().getObjectAt(0)).getDate();

    if (date != null) {
        Date notAfter = cert.getNotAfter();
        Date notBefore = cert.getNotBefore();
        if (notAfter != null && date.compareTo(notAfter) > 0) {
            throw new Exception(
                    "Signature verification failed (bad signing time) for " + cert.getSubjectDN().toString());
        }
        if (notBefore != null && date.compareTo(notBefore) < 0) {
            throw new Exception(
                    "Signature verification failed (bad signing time) for " + cert.getSubjectDN().toString());
        }
    }
}

From source file:org.signserver.module.tsa.TimeStampSignerTest.java

License:Open Source License

private int testWithHash(final ASN1ObjectIdentifier hashAlgo) throws Exception {
    int reqid = random.nextInt();
    TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator();
    final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(hashAlgo,
            new byte[getHashLength(hashAlgo)], BigInteger.valueOf(100));

    byte[] requestBytes = timeStampRequest.getEncoded();

    GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes);

    final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER1, signRequest,
            new RequestContext());

    final CertificateFactory factory = CertificateFactory.getInstance("X.509");
    final X509Certificate cert = (X509Certificate) factory
            .generateCertificate(new ByteArrayInputStream(Base64.decode(CERTSTRING.getBytes())));

    TimeStampResponse timeStampResponse = null;
    try {/* w w  w. jav a  2s. c om*/
        // check response
        timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData());
        timeStampResponse.validate(timeStampRequest);

        if (timeStampResponse.getStatus() != PKIStatus.GRANTED) {
            // return early and don't attempt to get a token
            return timeStampResponse.getStatus();
        }

        // check the hash value from the response
        TimeStampToken token = timeStampResponse.getTimeStampToken();
        AlgorithmIdentifier algo = token.getTimeStampInfo().getHashAlgorithm();
        assertEquals("Timestamp response is using incorrect hash algorithm", hashAlgo, algo.getAlgorithm());

        Collection signerInfos = token.toCMSSignedData().getSignerInfos().getSigners();

        // there should be one SignerInfo
        assertEquals("There should only be one signer in the timestamp response", 1, signerInfos.size());

        for (Object o : signerInfos) {
            SignerInformation si = (SignerInformation) o;

            // test the response signature algorithm
            assertEquals("Timestamp used unexpected signature algorithm", TSPAlgorithms.SHA1.toString(),
                    si.getDigestAlgOID());
            assertEquals("Timestamp is signed with unexpected signature encryption algorithm",
                    "1.2.840.113549.1.1.1", si.getEncryptionAlgOID());

            final AttributeTable attrs = si.getSignedAttributes();
            final ASN1EncodableVector scAttrs = attrs.getAll(PKCSObjectIdentifiers.id_aa_signingCertificate);

            assertEquals("Should contain a signingCertificate signed attribute", 1, scAttrs.size());

            TestUtils.checkSigningCertificateAttribute(ASN1Sequence.getInstance(scAttrs.get(0)), cert);
        }

    } catch (TSPException e) {
        fail("Failed to verify response");
    } catch (IOException e) {
        fail("Failed to verify response");
    }

    final TimeStampToken token = timeStampResponse.getTimeStampToken();

    try {

        token.validate(cert, "BC");

    } catch (TSPException e) {
        fail("Failed to validate response token");
    }

    return timeStampResponse.getStatus();
}

From source file:org.votingsystem.callable.MessageTimeStamper.java

License:Open Source License

public byte[] getDigestToken() {
    if (timeStampToken == null)
        return null;
    CMSSignedData tokenCMSSignedData = timeStampToken.toCMSSignedData();
    Collection signers = tokenCMSSignedData.getSignerInfos().getSigners();
    SignerInformation tsaSignerInfo = (SignerInformation) signers.iterator().next();
    AttributeTable signedAttrTable = tsaSignerInfo.getSignedAttributes();
    ASN1EncodableVector v = signedAttrTable.getAll(CMSAttributes.messageDigest);
    Attribute t = (Attribute) v.get(0);
    ASN1Set attrValues = t.getAttrValues();
    DERObject validMessageDigest = attrValues.getObjectAt(0).getDERObject();
    ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;
    byte[] digestToken = signedMessageDigest.getOctets();
    //String digestTokenStr = new String(Base64.encode(digestToken));
    //log.info(" digestTokenStr: " + digestTokenStr);
    return digestToken;
}

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

License:Open Source License

public TimeStampRequest getTimeStampRequest() throws Exception {
    SignerInformation signerInformation = ((SignerInformation) getSmimeSigned().getSignerInfos().getSigners()
            .iterator().next());/*from  ww w .  j ava  2s  . com*/
    AttributeTable table = signerInformation.getSignedAttributes();
    Attribute hash = table.get(CMSAttributes.messageDigest);
    ASN1OctetString as = ((ASN1OctetString) hash.getAttrValues().getObjectAt(0));
    TimeStampRequestGenerator reqgen = new TimeStampRequestGenerator();
    //reqgen.setReqPolicy(m_sPolicyOID);
    return reqgen.generate(signerInformation.getDigestAlgOID(), as.getOctets(),
            BigInteger.valueOf(KeyGeneratorVS.INSTANCE.getNextRandomInt()));
}

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

License:Open Source License

public static Date getSigningTime(SignerInformation signerInformation) {
    AttributeTable signedAttr = signerInformation.getSignedAttributes();
    Attribute signingTime = signedAttr.get(CMSAttributes.signingTime);
    if (signingTime != null) {
        try {//from w w w.  j ava2  s .c o m
            Enumeration en = signingTime.getAttrValues().getObjects();
            while (en.hasMoreElements()) {
                Object obj = en.nextElement();
                if (obj instanceof ASN1UTCTime) {
                    ASN1UTCTime asn1Time = (ASN1UTCTime) obj;
                    return asn1Time.getDate();
                } else if (obj instanceof DERUTCTime) {
                    DERUTCTime derTime = (DERUTCTime) obj;
                    return derTime.getDate();
                }
            }
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
    return null;
}

From source file:org.votingsystem.signature.util.CMSUtils.java

License:Open Source License

public static byte[] getSignerDigest(SignerInformation signer) throws CMSException {
    DERObject derObject = CMSUtils.getSingleValuedSignedAttribute(signer.getSignedAttributes(),
            CMSAttributes.messageDigest, "message-digest");
    ASN1OctetString signedMessageDigest = (ASN1OctetString) derObject;
    return signedMessageDigest.getOctets();
}

From source file:org.votingsystem.signature.util.CMSUtils.java

License:Open Source License

public static byte[] getDigestToken(TimeStampToken timeStampToken) {
    if (timeStampToken == null)
        return null;
    CMSSignedData tokenCMSSignedData = timeStampToken.toCMSSignedData();
    Collection signers = tokenCMSSignedData.getSignerInfos().getSigners();
    SignerInformation tsaSignerInfo = (SignerInformation) signers.iterator().next();

    AttributeTable signedAttrTable = tsaSignerInfo.getSignedAttributes();
    ASN1EncodableVector v = signedAttrTable.getAll(CMSAttributes.messageDigest);
    Attribute t = (Attribute) v.get(0);
    ASN1Set attrValues = t.getAttrValues();
    DERObject validMessageDigest = attrValues.getObjectAt(0).getDERObject();

    ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest;
    byte[] digestToken = signedMessageDigest.getOctets();
    //String digestTokenStr = new String(Base64.encode(digestToken));
    return digestToken;
}

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 av a2 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 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  w  w  w. j  a v a 2 s  .  co 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;
}