Example usage for org.bouncycastle.asn1.cms EnvelopedData getInstance

List of usage examples for org.bouncycastle.asn1.cms EnvelopedData getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms EnvelopedData getInstance.

Prototype

public static EnvelopedData getInstance(Object obj) 

Source Link

Document

Return an EnvelopedData object from the given object.

Usage

From source file:com.novosec.pkix.asn1.crmf.EncryptedKey.java

License:Open Source License

public EncryptedKey(DEREncodable derObj, int tag) {
    this.tagNo = tag;

    if (derObj instanceof EnvelopedData) {
        this.obj = (EnvelopedData) derObj;
    } else if (derObj instanceof EncryptedValue) {
        this.encryptedValue = (EncryptedValue) derObj;
    } else {//from  www .  j  av  a  2 s  .co m
        switch (this.tagNo) {
        case TAGNO_ENV_DATA:
            this.obj = EnvelopedData.getInstance(derObj);
            break;
        default:
            this.encryptedValue = EncryptedValue.getInstance(derObj);
            break;
        }
    }
}

From source file:com.novosec.pkix.asn1.crmf.EncryptedKey.java

License:Open Source License

public EnvelopedData getEnvelopedData() {
    return EnvelopedData.getInstance(obj);
}

From source file:es.gob.afirma.applet.CMSInformation.java

License:Open Source License

/**
 * Obtiene la información de diferentes tipos de formatos.
 * @param doj Etiqueta ASN.1 de la que se obtienen los datos.
 * @param envelopeType   Tipo de formato:
 * <li>0: EnvelopedData</li>
 * <li>1: AuthenticatedData</li>
 * <li>2: AuthEnvelopedData</li>
 * <li>3: SignedAndEnvelopedData</li>
 * <li>4: SignedData</li>/* w w w . j a  v a 2 s.c om*/
 * <li>5: Encrypted</li>
 * @param tipoDetalle   Tipo de datos (literal)
 * @param signBinaryType Tipo de firmado binario (CADES o CMS)
 * @return  Representaci&oacute;n de los datos.
 */
private static String extractData(final ASN1TaggedObject doj, final int envelopeType, final String tipoDetalle,
        final int signBinaryType) {
    String detalle = ""; //$NON-NLS-1$
    detalle = detalle + tipoDetalle + CR;

    ASN1Set rins = null;
    EncryptedContentInfo encryptedContentInfo = null;
    ASN1Set unprotectedAttrs = null;
    ASN1Integer version = null;
    AlgorithmIdentifier aid = null;
    ContentInfo ci = null;
    ASN1Set authAttrs = null;
    ASN1Set ds = null;
    ASN1Set signerInfosSd = null;

    switch (envelopeType) {
    case TYPE_ENVELOPED_DATA:
        final EnvelopedData enveloped = EnvelopedData.getInstance(doj.getObject());
        version = enveloped.getVersion();
        rins = enveloped.getRecipientInfos();
        encryptedContentInfo = enveloped.getEncryptedContentInfo();
        unprotectedAttrs = enveloped.getUnprotectedAttrs();
        break;
    case TYPE_AUTHENTICATED_DATA:
        final AuthenticatedData authenticated = AuthenticatedData.getInstance(doj.getObject());
        version = authenticated.getVersion();
        rins = authenticated.getRecipientInfos();
        aid = authenticated.getMacAlgorithm();
        ci = authenticated.getEncapsulatedContentInfo();
        authAttrs = authenticated.getAuthAttrs();
        unprotectedAttrs = authenticated.getUnauthAttrs();
        break;
    case TYPE_AUTHENTICATED_ENVELOPED_DATA:
        final AuthEnvelopedData authEnveloped = AuthEnvelopedData.getInstance(doj.getObject());
        version = authEnveloped.getVersion();
        rins = authEnveloped.getRecipientInfos();
        encryptedContentInfo = authEnveloped.getAuthEncryptedContentInfo();
        authAttrs = authEnveloped.getAuthAttrs();
        unprotectedAttrs = authEnveloped.getUnauthAttrs();
        break;
    case TYPE_SIGNED_ENVELOPED_DATA:
        final SignedAndEnvelopedData signedEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject());
        version = signedEnv.getVersion();
        rins = signedEnv.getRecipientInfos();
        encryptedContentInfo = signedEnv.getEncryptedContentInfo();
        signerInfosSd = signedEnv.getSignerInfos();
        break;
    case TYPE_SIGNED_DATA:
        final SignedData signed = SignedData.getInstance(doj.getObject());
        version = signed.getVersion();
        ds = signed.getDigestAlgorithms();
        ci = signed.getEncapContentInfo();
        signerInfosSd = signed.getSignerInfos();
        break;
    case TYPE_ENCRYPTED_DATA:
        final ASN1Sequence encrypted = (ASN1Sequence) doj.getObject();
        version = ASN1Integer.getInstance(encrypted.getObjectAt(0));
        encryptedContentInfo = EncryptedContentInfo.getInstance(encrypted.getObjectAt(1));
        if (encrypted.size() == 3) {
            unprotectedAttrs = (ASN1Set) encrypted.getObjectAt(2);
        }
        break;
    default:
        throw new IllegalArgumentException("Tipo de sobre no soportado: " + envelopeType); //$NON-NLS-1$
    }

    //obtenemos la version
    detalle = detalle + AppletMessages.getString("CMSInformation.1") + SP + version + CR; //$NON-NLS-1$

    //recipientInfo
    if (rins != null) {
        if (envelopeType != TYPE_SIGNED_DATA && envelopeType != TYPE_ENCRYPTED_DATA && rins.size() > 0) {
            detalle = detalle + AppletMessages.getString("CMSInformation.13") + CR; //$NON-NLS-1$
        }
        for (int i = 0; i < rins.size(); i++) {
            final KeyTransRecipientInfo kti = KeyTransRecipientInfo
                    .getInstance(RecipientInfo.getInstance(rins.getObjectAt(i)).getInfo());
            detalle = detalle + AppletMessages.getString("CMSInformation.14") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$
            final AlgorithmIdentifier diAlg = kti.getKeyEncryptionAlgorithm();

            //issuer y serial
            final IssuerAndSerialNumber iss = (IssuerAndSerialNumber) SignerIdentifier
                    .getInstance(kti.getRecipientIdentifier().getId()).getId();
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$
                    + iss.getName().toString() + CR;
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$
                    + CR;

            // el algoritmo de cifrado de los datos
            AOCipherAlgorithm algorithm = null;
            final AOCipherAlgorithm[] algos = AOCipherAlgorithm.values();

            // obtenemos el algoritmo usado para cifrar la pass
            for (final AOCipherAlgorithm algo : algos) {
                if (algo.getOid().equals(diAlg.getAlgorithm().toString())) {
                    algorithm = algo;
                }
            }
            if (algorithm != null) {
                detalle = detalle + TB + AppletMessages.getString("CMSInformation.17") + SP //$NON-NLS-1$
                        + algorithm.getName() + CR;
            } else {
                detalle = detalle + TB + AppletMessages.getString("CMSInformation.18") + SP //$NON-NLS-1$
                        + diAlg.getAlgorithm() + CR;
            }
        }
    }

    if (envelopeType == TYPE_ENVELOPED_DATA || envelopeType == TYPE_ENCRYPTED_DATA) {
        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);
    } else if (envelopeType == TYPE_AUTHENTICATED_DATA && aid != null && ci != null) {
        // mac algorithm
        detalle = detalle + AppletMessages.getString("CMSInformation.20") + SP + aid.getAlgorithm() + CR; //$NON-NLS-1$

        //digestAlgorithm
        final ASN1Sequence seq = (ASN1Sequence) doj.getObject();
        final ASN1TaggedObject da = (ASN1TaggedObject) seq.getObjectAt(4);
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObject());
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$

        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$

        detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs);
    } else if (envelopeType == TYPE_AUTHENTICATED_ENVELOPED_DATA) {
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);

        detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs);
    } else if (envelopeType == TYPE_SIGNED_ENVELOPED_DATA) {
        //algoritmo de firma
        final ASN1Sequence seq = (ASN1Sequence) doj.getObject();
        final ASN1Set da = (ASN1Set) seq.getObjectAt(2);
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObjectAt(0));
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$

        //obtenemos datos de los datos cifrados.
        detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$
        detalle = detalle + getEncryptedContentInfo(encryptedContentInfo);
    } else if (envelopeType == TYPE_SIGNED_DATA && ci != null && ds != null) {
        //algoritmo de firma
        final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(ds.getObjectAt(0));
        detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$
        detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$
    }

    //obtenemos lo atributos opcionales
    if (envelopeType != TYPE_SIGNED_ENVELOPED_DATA) {
        if (unprotectedAttrs == null) {
            detalle = detalle + AppletMessages.getString("CMSInformation.28") + CR; //$NON-NLS-1$
        } else {
            final String atributos = getUnSignedAttributes(unprotectedAttrs.getObjects());
            detalle = detalle + AppletMessages.getString("CMSInformation.29") + CR; //$NON-NLS-1$
            detalle = detalle + atributos;
        }
    } else if ((envelopeType == TYPE_SIGNED_ENVELOPED_DATA || envelopeType == TYPE_SIGNED_DATA)
            && signerInfosSd != null) {
        //obtenemos el(los) firmate(s)
        if (signerInfosSd.size() > 0) {
            detalle = detalle + AppletMessages.getString("CMSInformation.30") + CR; //$NON-NLS-1$
        }
        for (int i = 0; i < signerInfosSd.size(); i++) {
            final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i));

            detalle = detalle + AppletMessages.getString("CMSInformation.31") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$
            // version
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.1") + SP + si.getVersion() + CR; //$NON-NLS-1$
            //signerIdentifier
            final SignerIdentifier sident = si.getSID();
            final IssuerAndSerialNumber iss = IssuerAndSerialNumber.getInstance(sident.getId());
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$
                    + iss.getName().toString() + CR;
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$
                    + CR;

            //digestAlgorithm
            final AlgorithmIdentifier algId = si.getDigestAlgorithm();
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.35") + SP + algId.getAlgorithm() //$NON-NLS-1$
                    + CR;

            //obtenemos lo atributos obligatorios
            final ASN1Set sa = si.getAuthenticatedAttributes();
            String satributes = ""; //$NON-NLS-1$
            if (sa != null) {
                satributes = getsignedAttributes(sa, signBinaryType);
            }
            detalle = detalle + TB + AppletMessages.getString("CMSInformation.36") + CR; //$NON-NLS-1$
            detalle = detalle + satributes;
        }
    }
    return detalle;
}

From source file:es.gob.afirma.envelopers.cms.CMSDecipherEnvelopData.java

License:Open Source License

/** &Eacute;ste m&eacute;todo descifra el contenido de un CMS EnvelopedData.
 * @param cmsData/*ww w . j a v a2s  . co m*/
 *        Flujo de lectura de los datos que contienen el tipo
 *        EnvelopedData para obtener los datos cifrados.
 * @param keyEntry
 *        Clave privada del certificado usado para descifrar el
 *        contenido.
 * @return El contenido descifrado del EnvelopedData.
 * @throws java.io.IOException
 *         Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *         datos
 * @throws java.security.cert.CertificateEncodingException
 *         Si se produce alguna excepci&oacute;n con los certificados de
 *         firma.
 * @throws AOException
 *         Cuando ocurre un error durante el proceso de descifrado
 *         (formato o clave incorrecto,...)
 * @throws AOInvalidRecipientException
 *         Cuando se indica un certificado que no est&aacute; entre los
 *         destinatarios del sobre.
 * @throws InvalidKeyException
 *         Cuando la clave almacenada en el sobre no es v&aacute;lida.
 * @throws NoSuchPaddingException Cuando no se soporta un tipo de relleno necesario.
 * @throws NoSuchAlgorithmException Si el JRE no soporta alg&uacute;n algoritmo necesario
 * @throws BadPaddingException Cuando hay problemas con un relleno de datos.
 * @throws IllegalBlockSizeException Cuando hay problemas internos con los tama&ntilde;os de bloque de cifrado.
 * @throws InvalidAlgorithmParameterException Si no se soporta un par&aacute;metro necesario para un algoritmo. */
public static byte[] dechiperEnvelopData(final byte[] cmsData, final PrivateKeyEntry keyEntry)
        throws IOException, CertificateEncodingException, AOException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {

    // Contendra el contenido a tratar.
    EnvelopedData enveloped = null;
    Enumeration<?> elementRecipient;

    try {
        // Contenido de EnvelopedData
        final ASN1Sequence contentEnvelopedData = Utils.fetchWrappedData(cmsData);

        enveloped = EnvelopedData.getInstance(contentEnvelopedData);
        elementRecipient = enveloped.getRecipientInfos().getObjects();
    } catch (final Exception ex) {
        throw new AOException("El fichero no contiene un tipo EnvelopedData", ex); //$NON-NLS-1$
    }

    final EncryptedKeyDatas encryptedKeyDatas = Utils
            .fetchEncryptedKeyDatas((X509Certificate) keyEntry.getCertificate(), elementRecipient);

    // Obtenemos el contenido cifrado
    final EncryptedContentInfo contenidoCifrado = enveloped.getEncryptedContentInfo();

    // Obtenemos el algoritmo usado para cifrar la clave generada.
    final AlgorithmIdentifier algClave = contenidoCifrado.getContentEncryptionAlgorithm();

    // Asignamos la clave de descifrado del contenido.
    final KeyAsigned keyAsigned = Utils.assignKey(encryptedKeyDatas.getEncryptedKey(), keyEntry, algClave);

    // Desciframos el contenido.
    return Utils.deCipherContent(contenidoCifrado.getEncryptedContent().getOctets(), keyAsigned.getConfig(),
            keyAsigned.getCipherKey());
}

From source file:es.gob.afirma.envelopers.cms.CMSEnvelopedData.java

License:Open Source License

/** M&eacute;todo que inserta remitentes en el "OriginatorInfo" de un sobre
 * de tipo envelopedData./* w ww . j a va2 s.  com*/
 * @param data
 *        Datos CMS que admiten multiples remitentes/firmantes.
 * @param signerCertificateChain
 *        Cadena de certificados a agregar.
 * @return La nueva firma enveloped con los remitentes que ten&iacute;a (si
 *         los tuviera) con la cadena de certificados nueva.
 * @throws IOException Si hay errores de lectura de datos
 * @throws CertificateEncodingException Cuando el certificado proporcionado es inv&aacute;lido */
public static byte[] addOriginatorInfo(final byte[] data, final X509Certificate[] signerCertificateChain)
        throws IOException, CertificateEncodingException {

    final ASN1InputStream is = new ASN1InputStream(data);
    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
    is.close();
    final Enumeration<?> e = dsq.getObjects();
    // Elementos que contienen los elementos OID Data
    final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement();
    if (doi.equals(PKCSObjectIdentifiers.envelopedData)) {
        // Contenido de Data
        final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

        final EnvelopedData ed = EnvelopedData.getInstance(doj.getObject());

        // Obtenemos los originatorInfo
        OriginatorInfo origInfo = ed.getOriginatorInfo();
        ASN1Set certs = null;
        if (origInfo != null) {
            certs = origInfo.getCertificates();
        }

        // Si no hay certificados, se deja como esta.
        final OriginatorInfo origInfoChecked = Utils.checkCertificates(signerCertificateChain, certs);
        if (origInfoChecked != null) {
            origInfo = origInfoChecked;
        }

        // Se crea un nuevo EnvelopedData a partir de los datos
        // anteriores con los nuevos originantes.
        return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo,
                ed.getRecipientInfos(), ed.getEncryptedContentInfo(), ed.getUnprotectedAttrs()))
                        .getEncoded(ASN1Encoding.DER);
    }

    return null;
}

From source file:es.gob.afirma.envelopers.cms.ValidateCMS.java

License:Open Source License

/** M&eacute;todo que verifica que es una firma de tipo "Enveloped data"
 * @param data/*from   ww w  .j a v  a 2  s.  com*/
 *        Datos CMS.
 * @return si es de este tipo. */
static boolean isCMSEnvelopedData(final byte[] data) {
    boolean isValid = true;
    try {
        final ASN1InputStream is = new ASN1InputStream(data);
        final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
        is.close();
        final Enumeration<?> e = dsq.getObjects();
        // Elementos que contienen los elementos OID Data
        final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement();
        if (!doi.equals(PKCSObjectIdentifiers.envelopedData)) {
            isValid = false;
        } else {
            // Contenido de Data
            final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();
            /*
             * Si no se construye el objeto correctamente, se pasa al manejo
             * de la excepcion
             */
            EnvelopedData.getInstance(doj.getObject());
        }

    } catch (final Exception ex) {
        isValid = false;
    }

    return isValid;
}

From source file:es.gob.afirma.signers.cades.CAdESValidator.java

License:Open Source License

/** Verifica si los datos proporcionados se corresponden con una estructura de tipo <i>EnvelopedData</i>.
 * @param data Datos PKCS#7/CMS/CAdES./*from  w w  w.  j av  a 2s. c  om*/
 * @return <code>true</code> si los datos proporcionados se corresponden con una estructura de tipo <i>EnvelopedData</i>,
 * <code>false</code> en caso contrario.
 * @throws IOException Si ocurren problemas relacionados con la lectura de los datos */
static boolean isCAdESEnvelopedData(final byte[] data) throws IOException {
    boolean isValid = false;

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    final ASN1InputStream is = new ASN1InputStream(data);
    final ASN1Sequence dsq;
    try {
        dsq = (ASN1Sequence) is.readObject();
    } catch (final Exception e) {
        // No es una secuencia valida
        return false;
    } finally {
        is.close();
    }
    final Enumeration<?> e = dsq.getObjects();
    // Elementos que contienen los elementos OID Data
    final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement();
    if (doi.equals(PKCSObjectIdentifiers.envelopedData)) {
        isValid = true;
    }
    // Contenido de Data
    final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

    try {
        /* los retornos no se usan, solo es para verificar que la conversion
         * ha sido correcta. De no ser asi, se pasaria al manejo de la
         * excepcion. */
        EnvelopedData.getInstance(doj.getObject());
    } catch (final Exception ex) {
        LOGGER.info("Los datos proporcionados no son de tipo EnvelopedData: " + ex); //$NON-NLS-1$
        return false;
    }

    return isValid;
}

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

License:Open Source License

private void init() throws IOException {
    if (log.isTraceEnabled()) {
        log.trace(">init");
    }/*ww  w  .j  a  v a  2 s .c o m*/
    try {
        CMSSignedData csd = new CMSSignedData(scepmsg);
        SignerInformationStore infoStore = csd.getSignerInfos();
        @SuppressWarnings("unchecked")
        Collection<SignerInformation> signers = infoStore.getSigners();
        Iterator<SignerInformation> iter = signers.iterator();
        if (iter.hasNext()) {
            SignerInformation si = (SignerInformation) iter.next();
            preferredDigestAlg = si.getDigestAlgOID();
            log.debug("Set " + preferredDigestAlg + " as preferred digest algorithm for SCEP");
        }
    } catch (CMSException e) {
        // ignore, use default digest algo
        log.error("CMSException trying to get preferred digest algorithm: ", e);
    }
    // Parse and verify the integrity of the PKIOperation message PKCS#7
    /* If this would have been done using the newer CMS it would have made me so much happier... */
    ASN1InputStream seqAsn1InputStream = new ASN1InputStream(new ByteArrayInputStream(scepmsg));
    ASN1Sequence seq = null;
    try {
        seq = (ASN1Sequence) seqAsn1InputStream.readObject();
    } finally {
        seqAsn1InputStream.close();
    }
    ContentInfo ci = ContentInfo.getInstance(seq);
    String ctoid = ci.getContentType().getId();

    if (ctoid.equals(CMSObjectIdentifiers.signedData.getId())) {
        // This is SignedData so it is a pkcsCertReqSigned, pkcsGetCertInitialSigned, pkcsGetCertSigned, pkcsGetCRLSigned
        // (could also be pkcsRepSigned or certOnly, but we don't receive them on the server side
        // Try to find out what kind of message this is
        sd = SignedData.getInstance((ASN1Sequence) ci.getContent());
        // Get self signed cert to identify the senders public key
        ASN1Set certs = sd.getCertificates();
        if (certs.size() > 0) {
            // There should be only one...
            ASN1Encodable dercert = certs.getObjectAt(0);
            if (dercert != null) {
                // Requester's self-signed certificate is requestKeyInfo
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                DEROutputStream dOut = new DEROutputStream(bOut);
                dOut.writeObject(dercert);
                if (bOut.size() > 0) {
                    requestKeyInfo = bOut.toByteArray();
                    //Create Certificate used for debugging
                    try {
                        signercert = CertTools.getCertfromByteArray(requestKeyInfo);
                        if (log.isDebugEnabled()) {
                            log.debug("requestKeyInfo is SubjectDN: " + CertTools.getSubjectDN(signercert)
                                    + ", Serial=" + CertTools.getSerialNumberAsString(signercert)
                                    + "; IssuerDN: " + CertTools.getIssuerDN(signercert).toString());
                        }
                    } catch (CertificateException e) {
                        log.error("Error parsing requestKeyInfo : ", e);
                    }

                }
            }
        }

        Enumeration<?> sis = sd.getSignerInfos().getObjects();

        if (sis.hasMoreElements()) {
            SignerInfo si = SignerInfo.getInstance((ASN1Sequence) sis.nextElement());
            Enumeration<?> attr = si.getAuthenticatedAttributes().getObjects();

            while (attr.hasMoreElements()) {
                Attribute a = Attribute.getInstance((ASN1Sequence) attr.nextElement());
                if (log.isDebugEnabled()) {
                    log.debug("Found attribute: " + a.getAttrType().getId());
                }
                if (a.getAttrType().getId().equals(id_senderNonce)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    ASN1OctetString str = ASN1OctetString.getInstance(values.nextElement());
                    senderNonce = new String(Base64.encode(str.getOctets(), false));
                    if (log.isDebugEnabled()) {
                        log.debug("senderNonce = " + senderNonce);
                    }
                }
                if (a.getAttrType().getId().equals(id_transId)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
                    transactionId = str.getString();
                    if (log.isDebugEnabled()) {
                        log.debug("transactionId = " + transactionId);
                    }
                }
                if (a.getAttrType().getId().equals(id_messageType)) {
                    Enumeration<?> values = a.getAttrValues().getObjects();
                    DERPrintableString str = DERPrintableString.getInstance(values.nextElement());
                    messageType = Integer.parseInt(str.getString());
                    if (log.isDebugEnabled()) {
                        log.debug("messagetype = " + messageType);
                    }
                }
            }
        }

        // If this is a PKCSReq
        if ((messageType == ScepRequestMessage.SCEP_TYPE_PKCSREQ)
                || (messageType == ScepRequestMessage.SCEP_TYPE_GETCRL)
                || (messageType == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL)) {
            // Extract the contents, which is an encrypted PKCS10 if messageType == 19
            // , and an encrypted issuer and subject if messageType == 20 (not extracted)
            // and an encrypted IssuerAndSerialNumber if messageType == 22
            ci = sd.getEncapContentInfo();
            ctoid = ci.getContentType().getId();

            if (ctoid.equals(CMSObjectIdentifiers.data.getId())) {
                ASN1OctetString content = (ASN1OctetString) ci.getContent();
                if (log.isDebugEnabled()) {
                    log.debug("envelopedData is " + content.getOctets().length + " bytes.");
                }
                ASN1InputStream seq1Asn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(content.getOctets()));
                ASN1Sequence seq1 = null;
                try {
                    seq1 = (ASN1Sequence) seq1Asn1InputStream.readObject();
                } finally {
                    seq1Asn1InputStream.close();
                }
                envEncData = ContentInfo.getInstance(seq1);
                ctoid = envEncData.getContentType().getId();

                if (ctoid.equals(CMSObjectIdentifiers.envelopedData.getId())) {
                    envData = EnvelopedData.getInstance((ASN1Sequence) envEncData.getContent());
                    ASN1Set recipientInfos = envData.getRecipientInfos();
                    Enumeration<?> e = recipientInfos.getObjects();
                    while (e.hasMoreElements()) {
                        RecipientInfo ri = RecipientInfo.getInstance(e.nextElement());
                        KeyTransRecipientInfo recipientInfo = KeyTransRecipientInfo.getInstance(ri.getInfo());
                        RecipientIdentifier rid = recipientInfo.getRecipientIdentifier();
                        IssuerAndSerialNumber iasn = IssuerAndSerialNumber.getInstance(rid.getId());
                        issuerDN = iasn.getName().toString();
                        serialNo = iasn.getSerialNumber().getValue();
                        if (log.isDebugEnabled()) {
                            log.debug("IssuerDN: " + issuerDN);
                            log.debug("SerialNumber: " + iasn.getSerialNumber().getValue().toString(16));
                        }
                    }
                } else {
                    errorText = "EncapsulatedContentInfo does not contain PKCS7 envelopedData: ";
                    log.error(errorText + ctoid);
                    error = 2;
                }
            } else {
                errorText = "EncapsulatedContentInfo is not of type 'data': ";
                log.error(errorText + ctoid);
                error = 3;
            }
        } else {
            errorText = "This is not a certification request!";
            log.error(errorText);
            error = 4;
        }
    } else {
        errorText = "PKCSReq does not contain 'signedData': ";
        log.error(errorText + ctoid);
        error = 1;
    }

    log.trace("<init");
}