Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

List of usage examples for org.bouncycastle.asn1 ASN1InputStream readObject

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream readObject.

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:ec.gov.informatica.firmadigital.signature.BouncyCastleSignatureProcessor.java

License:Open Source License

/**
 *  <code> crearDatosUsuario </code>
 * @param signingCert/*from  w  w  w.  j  av  a 2  s  .c om*/
 * @return
 * Esta funcion llena los datos del usuario encontrados en el certificado
 */
private DatosUsuario crearDatosUsuario(X509Certificate signingCert) {
    //        depuracionActual.info("Libreria: Esta en crearDatosUsuario : ");
    DatosUsuario datosUsuario = new DatosUsuario();
    if (signingCert.getExtensionValue("1.2.3.4.1") != null) {
        datosUsuario.setCedula(new String(signingCert.getExtensionValue("1.2.3.4.1")).trim());
    }
    if (signingCert.getExtensionValue("1.2.3.4.2") != null) {
        datosUsuario.setNombre(new String(signingCert.getExtensionValue("1.2.3.4.2")).trim());
    }
    if (signingCert.getExtensionValue("1.2.3.4.3") != null) {
        String txtNombre = new String(signingCert.getExtensionValue("1.2.3.4.3")).trim();
        if (signingCert.getExtensionValue("1.2.3.4.4") != null)
            txtNombre = txtNombre + " " + new String(signingCert.getExtensionValue("1.2.3.4.4")).trim();
        datosUsuario.setApellido(txtNombre);
    }
    if (signingCert.getExtensionValue("1.2.3.4.6") != null) {
        datosUsuario.setInstitucion(new String(signingCert.getExtensionValue("1.2.3.4.6")).trim());
    }
    if (signingCert.getExtensionValue("1.2.3.4.5") != null) {
        datosUsuario.setCargo(new String(signingCert.getExtensionValue("1.2.3.4.5")).trim());
    }

    if (signingCert.getSerialNumber() != null) {
        datosUsuario.setSerial(signingCert.getSerialNumber().toString());
    }

    if (signingCert.getExtensionValue("2.5.29.31") != null) {

        //Estas declaraciones buscan un atributo del Certificado (lista CRL) que permite buscar en revocados.
        byte[] val1 = signingCert.getExtensionValue("2.5.29.31");
        if (val1 == null) {
            if (signingCert.getSubjectDN().getName().equals(signingCert.getIssuerDN().getName())) {
                System.out.println(
                        "El certificado es un certificado raiz: " + signingCert.getSubjectDN().getName());
            } else {
                System.out.println("El certificado NO tiene punto de distribucin de CRL : "
                        + signingCert.getSubjectDN().getName());
            }
            //return Collections.emptyList();
        } else {
            //esta es la parte que deberas aumentar en si
            try {
                ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
                DERObject derObj = oAsnInStream.readObject();
                DEROctetString dos = (DEROctetString) derObj;
                byte[] val2 = dos.getOctets();
                ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
                DERObject derObj2 = oAsnInStream2.readObject();
                List<String> urls = getDERValue(derObj2);

                for (int j = 0; j < urls.size(); j++) {
                    datosUsuario.setCrl(urls.get(7));
                }
                //                datosUsuario.setCrl( new String(   distrPoint.substring( distrPoint.indexOf("U")+8, distrPoint.indexOf("ldap") - 8 )     ).trim() );     //distrPoint.substring( distrPoint.indexOf("U")+8, distrPoint.indexOf("U") + 12 )
                System.out.println(urls);// .println(urls);
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
                e.printStackTrace();
            }
        } //fin else 

    }

    return datosUsuario;
}

From source file:ec.rubrica.cert.CertUtils.java

License:Open Source License

private static ASN1Primitive toDERObject(byte[] data) throws IOException {
    ByteArrayInputStream inStream = new ByteArrayInputStream(data);
    ASN1InputStream asnInputStream = null;

    try {//from   w  ww . j a v  a2  s  .  co  m
        asnInputStream = new ASN1InputStream(inStream);
        return asnInputStream.readObject();
    } finally {
        if (asnInputStream != null) {
            try {
                asnInputStream.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:ec.rubrica.util.BouncyCastleUtils.java

License:Open Source License

public static boolean certificateHasPolicy(X509Certificate cert, String sOid) {
    try {/*from  w ww.  j av a2s  .c  o  m*/
        logger.fine("Read cert policies: " + cert.getSerialNumber().toString());

        ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
        ASN1InputStream aIn = new ASN1InputStream(bIn);
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
        X509CertificateStructure obj = new X509CertificateStructure(seq);
        TBSCertificateStructure tbsCert = obj.getTBSCertificate();
        if (tbsCert.getVersion() == 3) {
            X509Extensions ext = tbsCert.getExtensions();
            if (ext != null) {
                Enumeration en = ext.oids();
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
                    X509Extension extVal = ext.getExtension(oid);
                    ASN1OctetString oct = extVal.getValue();
                    ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));

                    if (oid.equals(X509Extension.certificatePolicies)) {
                        ASN1Sequence cp = (ASN1Sequence) extIn.readObject();
                        for (int i = 0; i != cp.size(); i++) {
                            PolicyInformation pol = PolicyInformation.getInstance(cp.getObjectAt(i));
                            DERObjectIdentifier dOid = pol.getPolicyIdentifier();
                            String soid2 = dOid.getId();

                            logger.fine("Policy: " + soid2);
                            if (soid2.startsWith(sOid))
                                return true;
                        }
                    }
                }
            }

        }
    } catch (Exception ex) {
        logger.severe("Error reading cert policies: " + ex);
    }
    return false;
}

From source file:edu.vt.middleware.crypt.util.CryptReader.java

License:Open Source License

/**
 * Attempts to create a Bouncy Castle <code>DERObject</code> from a byte array
 * representing ASN.1 encoded data./*from  w w w . jav  a  2  s  . co  m*/
 *
 * @param  data  ASN.1 encoded data as byte array.
 * @param  discardWrapper  In some cases the value of the encoded data may
 * itself be encoded data, where the latter encoded data is desired. Recall
 * ASN.1 data is of the form {TAG, SIZE, DATA}. Set this flag to true to skip
 * the first two bytes, e.g. TAG and SIZE, and treat the remaining bytes as
 * the encoded data.
 *
 * @return  DER object.
 *
 * @throws  IOException  On I/O errors.
 */
public static DERObject readEncodedBytes(final byte[] data, final boolean discardWrapper) throws IOException {
    final ByteArrayInputStream inBytes = new ByteArrayInputStream(data);
    int size = data.length;
    if (discardWrapper) {
        inBytes.skip(2);
        size = data.length - 2;
    }

    final ASN1InputStream in = new ASN1InputStream(inBytes, size);
    try {
        return in.readObject();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            final Log logger = LogFactory.getLog(CryptReader.class);
            if (logger.isWarnEnabled()) {
                logger.warn("Error closing ASN.1 input stream.", e);
            }
        }
    }
}

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

License:Open Source License

/**
 * M&eacute;todo principal que obtiene la informaci&oacute;n a partir de un fichero firmado
 * de tipo CMS./* www. j av  a  2  s .c  o  m*/
 * @param data Objeto CMS.
 * @return Texto descriptivo del objeto CMS.
 * @throws IOException Si ocurre alg&uacute;n problema leyendo o escribiendo los datos
 * @throws AOInvalidFormatException Error de formato no v&aacute;lido.
 */
static String getInformation(final byte[] data) throws IOException, AOInvalidFormatException {

    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();

    // Contenido a obtener informacion
    final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

    final String datos;
    if (doi.equals(PKCSObjectIdentifiers.data)) {
        datos = AppletMessages.getString("CMSInformation.0") + SP + DATA + CR; //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.digestedData)) {
        datos = getFromDigestedData(doj);
    } else if (doi.equals(PKCSObjectIdentifiers.encryptedData)) {

        datos = extractData(doj, TYPE_ENCRYPTED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + ENCRYPTED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.signedData)) {
        datos = extractData(doj, TYPE_SIGNED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + SIGNED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.envelopedData)) {
        datos = extractData(doj, TYPE_ENVELOPED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.signedAndEnvelopedData)) {
        datos = extractData(doj, TYPE_SIGNED_ENVELOPED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + SIGNED_ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.id_ct_authData)) {
        datos = extractData(doj, TYPE_AUTHENTICATED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + AUTHENTICATED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(PKCSObjectIdentifiers.id_ct_authEnvelopedData)) {
        datos = extractData(doj, TYPE_AUTHENTICATED_ENVELOPED_DATA,
                AppletMessages.getString("CMSInformation.0") + SP + AUTH_ENVELOPED_DATA, BINARY_SIGN_CMS); //$NON-NLS-1$
    } else if (doi.equals(CMSObjectIdentifiers.compressedData)) {
        datos = getFromCompressedData(doj);
    } else {
        throw new AOInvalidFormatException(
                "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$
    }

    return datos;
}

From source file:es.gob.afirma.envelopers.cades.CAdESEPESSignedAndEnvelopedData.java

License:Open Source License

/** M&eacute;todo que inserta remitentes en el "OriginatorInfo" de un sobre
 * de tipo AuthenticatedEnvelopedData./*from ww w. j  a v  a  2 s .c om*/
 * @return La nueva firma AuthenticatedEnvelopedData con los remitentes que
 *         ten&iacute;a (si los tuviera) con la cadena de certificados
 *         nueva.
 * @throws IOException */
byte[] addOriginatorInfo(final InputStream data, final P7ContentSignerParameters parameters,
        final X509Certificate[] signerCertificateChain, final PrivateKeyEntry keyEntry, final AdESPolicy policy)
        throws IOException {
    // boolean isValid = false;
    byte[] retorno = null;

    // LEEMOS EL FICHERO QUE NOS INTRODUCEN
    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 DERObjectIdentifier doi = (DERObjectIdentifier) e.nextElement();
    if (doi.equals(PKCSObjectIdentifiers.signedAndEnvelopedData)) {
        // Contenido de Data
        final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

        final SignedAndEnvelopedData signEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject());

        // Obtenemos los originatorInfo
        final ASN1EncodableVector signerInfos = new ASN1EncodableVector();
        final Enumeration<?> signers = signEnv.getSignerInfos().getObjects();
        while (signers.hasMoreElements()) {
            signerInfos.add((ASN1Sequence) signers.nextElement());
        }

        ASN1EncodableVector signCerts = new ASN1EncodableVector();

        // Si no hay certificados, se deja como esta.
        if (signerCertificateChain.length != 0) {

            // algoritmo
            final String signatureAlgorithm;
            final String digestAlgorithm;
            final ASN1EncodableVector digestAlgs = new ASN1EncodableVector();

            signatureAlgorithm = parameters.getSignatureAlgorithm();
            digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm);

            AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));
            digestAlgs.add(digAlgId);

            final TBSCertificateStructure tbs2;
            try {
                tbs2 = TBSCertificateStructure.getInstance(
                        ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate()));
            } catch (final CertificateEncodingException ex) {
                throw new IOException("Error en la codificacion del certificado del firmante", ex); //$NON-NLS-1$
            }

            final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(
                    X500Name.getInstance(tbs2.getIssuer()), tbs2.getSerialNumber().getValue());

            final SignerIdentifier identifier = new SignerIdentifier(encSid);

            // AlgorithmIdentifier
            digAlgId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(AOAlgorithmID.getOID(digestAlgorithm)),
                    new DERNull());

            // // ATRIBUTOS
            final ASN1EncodableVector contextExpecific;
            try {
                contextExpecific = CAdESUtils.generateSignerInfo(signerCertificateChain[0], digestAlgorithm,
                        parameters.getContent(), policy, null);
            } catch (final CertificateEncodingException ex) {
                throw new IOException("Error en la codificacion del certificado del firmante", ex); //$NON-NLS-1$
            } catch (final NoSuchAlgorithmException ex) {
                throw new IOException("Error generacion del SignerInfo", ex); //$NON-NLS-1$
            }

            this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));
            final ASN1Set signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific));

            final ASN1Set unSignedAttr = null;

            // digEncryptionAlgorithm
            final SignerInfo nuevoSigner = CAdESUtils.signAndEnvelope(keyEntry, signatureAlgorithm, digAlgId,
                    identifier, signedAttr, unSignedAttr, "RSA", //$NON-NLS-1$
                    this.signedAttr2);

            // introducimos el nuevo Signer
            signerInfos.add(nuevoSigner);

            // LISTA DE CERTIFICADOS: obtenemos la lista de certificados
            try {
                signCerts = CAdESUtils.loadCertificatesList(signEnv, signerCertificateChain);
            } catch (final CertificateEncodingException ex) {
                throw new IOException("Error en la codificacion de los certificados del firmante", ex); //$NON-NLS-1$
            }
        } else {
            LOGGER.warning("No se ha podido obtener el certificado del nuevo firmante "); //$NON-NLS-1$
        }

        final ASN1Set certrevlist = null;

        // Se crea un nuevo AuthenticatedEnvelopedData a partir de los
        // datos anteriores con los nuevos originantes.
        retorno = new ContentInfo(PKCSObjectIdentifiers.signedAndEnvelopedData,
                new SignedAndEnvelopedData(signEnv.getRecipientInfos(), signEnv.getDigestAlgorithms(),
                        signEnv.getEncryptedContentInfo(), // encInfo,
                        new DERSet(signCerts), // certificates,
                        certrevlist, // certrevlist,
                        new DERSet(signerInfos))).getEncoded(ASN1Encoding.DER);
    }

    return retorno;
}

From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java

License:Open Source License

/** Obtiene el contenido de un archivo encriptado
 * @param file Archivo con los datos/*from  www  .j  a v  a 2 s  .  c o m*/
 * @param config Configuracion de cifrado
 * @param params Parametros
 * @param cipher Encriptador */
private static EncryptedContentInfo getEncryptedContentInfo(final byte[] file, final AOCipherConfig config,
        final AlgorithmParameterSpec params, final Cipher cipher) throws IOException {
    final byte[] ciphered;
    try {
        ciphered = cipher.doFinal(file);
    } catch (final Exception e) {
        LOGGER.severe("No se ha podido completar el cifrado, se devolvera null: " + e); //$NON-NLS-1$
        return null;
    }

    ASN1Encodable asn1Params;
    if (params != null) {
        final ASN1InputStream aIn = new ASN1InputStream(cipher.getParameters().getEncoded("ASN.1")); //$NON-NLS-1$
        asn1Params = aIn.readObject();
        aIn.close();
    } else {
        asn1Params = new DERNull();
    }

    // obtenemos el OID del algoritmo de cifrado
    final AlgorithmIdentifier encAlgId = new AlgorithmIdentifier(
            new ASN1ObjectIdentifier(config.getAlgorithm().getOid()), asn1Params);

    // Obtenemos el identificador
    final ASN1ObjectIdentifier contentType = PKCSObjectIdentifiers.encryptedData;
    return new EncryptedContentInfo(contentType, encAlgId, new DEROctetString(ciphered));
}

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

License:Open Source License

/** Recupera el contenido de un envoltorio CMS.
 * @param cmsEnvelop Envoltorio CMS.//w w  w. j a  v a  2s.  c o  m
 * @param addresseePke Clave privada del destinatario que desea desensobrar.
 * @return Contenido del envoltorio.
 * @throws InvalidKeyException Cuando la clave de descifrado configurada no sea v&aacute;lida o pertenezca a un destinatario.
 * @throws AOException Cuando se produce un error durante al desenvolver los datos.
 * @throws InvalidKeySpecException Cuando ocurren problemas relacionados con la estructura interna de las claves */
@Override
public byte[] recoverData(final byte[] cmsEnvelop, final PrivateKeyEntry addresseePke)
        throws InvalidKeyException, AOException, IOException, InvalidKeySpecException {

    final org.bouncycastle.asn1.ASN1InputStream is = new org.bouncycastle.asn1.ASN1InputStream(cmsEnvelop);

    // Leemos los datos
    final org.bouncycastle.asn1.ASN1Sequence dsq = (org.bouncycastle.asn1.ASN1Sequence) is.readObject();
    is.close();

    final Enumeration<?> objects = dsq.getObjects();

    // Elementos que contienen los elementos OID Data
    final org.bouncycastle.asn1.ASN1ObjectIdentifier doi = (org.bouncycastle.asn1.ASN1ObjectIdentifier) objects
            .nextElement();

    byte[] datos;
    try {
        if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.data)) {
            Logger.getLogger("es.gob.afirma") //$NON-NLS-1$
                    .warning("La extraccion de datos de los envoltorios CMS Data no esta implementada"); //$NON-NLS-1$
            datos = null;
        } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.digestedData)) {
            Logger.getLogger("es.gob.afirma") //$NON-NLS-1$
                    .warning("La extraccion de datos de los envoltorios CMS DigestedData no esta implementada"); //$NON-NLS-1$
            datos = null;
        } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.compressedData)) {
            datos = AOCMSEnveloper.recoverCMSCompressedData(cmsEnvelop);
        } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.encryptedData)) {
            datos = AOCMSEnveloper.recoverCMSEncryptedData(cmsEnvelop, this.cipherKey);
        } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.envelopedData)) {
            datos = AOCMSEnveloper.recoverCMSEnvelopedData(cmsEnvelop, addresseePke);
        } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authEnvelopedData)) {
            datos = AOCMSEnveloper.recoverCMSAuthenticatedEnvelopedData(cmsEnvelop, addresseePke);
        } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authenticatedData)) {
            datos = AOCMSEnveloper.recoverCMSAuthenticatedData(cmsEnvelop, addresseePke);
        } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.signedAndEnvelopedData)) {
            datos = AOCMSEnveloper.recoverCMSSignedEnvelopedData(cmsEnvelop, addresseePke);
        } else {
            throw new AOInvalidFormatException(
                    "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$
        }
    } catch (final AOInvalidRecipientException e) {
        throw new InvalidKeyException(
                "La clave indicada no pertenece a ninguno de los destinatarios del envoltorio", e); //$NON-NLS-1$
    } catch (final CertificateEncodingException e) {
        throw new AOException("Error al descodificar los certificados del envoltorio", e); //$NON-NLS-1$
    } catch (final NoSuchAlgorithmException e) {
        throw new AOException("No se reconoce el algoritmo indicado", e); //$NON-NLS-1$
    } catch (final NoSuchPaddingException e) {
        throw new AOException("No se reconoce el tipo de relleno indicado", e); //$NON-NLS-1$
    } catch (final InvalidAlgorithmParameterException e) {
        throw new AOException("No se reconoce la configuracion del algoritmo indicado", e); //$NON-NLS-1$
    } catch (final IllegalBlockSizeException e) {
        throw new AOException("Tamano de bloque invalido: " + e, e); //$NON-NLS-1$
    } catch (final BadPaddingException e) {
        throw new AOException("relleno invalido: " + e, e); //$NON-NLS-1$
    }

    return datos;
}

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

License:Open Source License

/** Recupera el contenido de un envoltorio CMS.
 * @param cmsEnvelop//from   ww  w  . ja  va 2  s  .com
 *        Envoltorio CMS.
 * @return Contenido del envoltorio.
 * @throws AOInvalidRecipientException
 *         Cuando el usuario no es uno de los destinatarios del sobre.
 * @throws InvalidKeyException Cuando la clave de descifrado configurada no es v&aacute;lida.
 * @throws CertificateEncodingException
 *         Cuando el certificado del destinatario no es v&aacute;lido.
 * @throws IOException
 *         Cuando el envoltorio est&aacute; corrupto o no puede leerse.
 * @throws AOInvalidFormatException
 *         Cuando no se ha indicado un envoltorio soportado.
 * @throws AOException
 *         Cuando se produce un error durante al desenvolver los datos.
 * @throws NoSuchAlgorithmException Si el JRE no soporta alg&uacute;n algoritmo necesario
 * @throws BadPaddingException Si hay problemas estableciendo el relleno de los datos
 * @throws IllegalBlockSizeException Si no cuadran los tama&ntilde;os de bloque de los algoritmos usados
 * @throws InvalidAlgorithmParameterException Si no se soporta alg&uacute;n par&aacute;metro necesario
 *                                            para alg&uacute;n algoritmo
 * @throws NoSuchPaddingException Si no se soporta alg&uacute;n m&eacute;todo de relleno
 * @throws InvalidKeySpecException Cuando ocurren problemas relacionados con la estructura interna de las claves */
byte[] recoverData(final byte[] cmsEnvelop)
        throws InvalidKeyException, CertificateEncodingException, IOException, AOException,
        NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException {

    final org.bouncycastle.asn1.ASN1InputStream is = new org.bouncycastle.asn1.ASN1InputStream(cmsEnvelop);

    // Leemos los datos
    final org.bouncycastle.asn1.ASN1Sequence dsq = (org.bouncycastle.asn1.ASN1Sequence) is.readObject();
    is.close();

    final Enumeration<?> objects = dsq.getObjects();

    // Elementos que contienen los elementos OID Data
    final org.bouncycastle.asn1.ASN1ObjectIdentifier doi = (org.bouncycastle.asn1.ASN1ObjectIdentifier) objects
            .nextElement();

    byte[] datos;
    if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.data)) {
        LOGGER.warning("La extraccion de datos de los envoltorios CMS Data no esta implementada"); //$NON-NLS-1$
        datos = null;
    } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.digestedData)) {
        LOGGER.warning("La extraccion de datos de los envoltorios CMS DigestedData no esta implementada"); //$NON-NLS-1$
        datos = null;
    } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.compressedData)) {
        datos = AOCMSMultiEnveloper.recoverCMSCompressedData(cmsEnvelop);
    } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.encryptedData)) {
        datos = AOCMSMultiEnveloper.recoverCMSEncryptedData(cmsEnvelop, this.cipherKey);
    } else if (doi.equals(org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers.envelopedData)) {
        datos = AOCMSMultiEnveloper.recoverCMSEnvelopedData(cmsEnvelop, this.configuredKe);
    } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authEnvelopedData)) {
        datos = AOCMSMultiEnveloper.recoverCMSAuthenticatedEnvelopedData(cmsEnvelop, this.configuredKe);
    } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.authenticatedData)) {
        datos = AOCMSMultiEnveloper.recoverCMSAuthenticatedData(cmsEnvelop, this.configuredKe);
    } else if (doi.equals(org.bouncycastle.asn1.cms.CMSObjectIdentifiers.signedAndEnvelopedData)) {
        datos = AOCMSMultiEnveloper.recoverCMSSignedEnvelopedData(cmsEnvelop, this.configuredKe);
    } else {
        throw new AOInvalidFormatException(
                "Los datos introducidos no se corresponden con un tipo de objeto CMS soportado"); //$NON-NLS-1$
    }

    return datos;
}

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

License:Open Source License

/** M&eacute;todo que inserta remitentes en el "OriginatorInfo" de un sobre
 * de tipo AuthenticatedData.//from www.j a  v a 2 s. c o m
 * @param data
 *        fichero que tiene la firma.
 * @param signerCertificateChain
 *        Cadena de certificados a agregar.
 * @return La nueva firma AuthenticatedData con los remitentes que
 *         ten&iacute;a (si los tuviera) con la cadena de certificados
 *         nueva.
 * @throws IOException Si hay errores de lectura o escritura de datos
 * @throws CertificateEncodingException Si el certificado del remitente es invalido */
static byte[] addOriginatorInfo(final InputStream 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.id_ct_authData)) {
        // Contenido de Data
        final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

        final AuthenticatedData auth = AuthenticatedData.getInstance(doj.getObject());

        final AlgorithmIdentifier digAlg = extractAOIfromAuth((ASN1Sequence) doj.getObject());

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

        final OriginatorInfo origInfoChecked = Utils.checkCertificates(signerCertificateChain, certs);
        if (origInfoChecked != null) {
            origInfo = origInfoChecked;
        }

        // Se crea un nuevo AuthenticatedData a partir de los datos
        // anteriores con los nuevos originantes.
        return new ContentInfo(PKCSObjectIdentifiers.id_ct_authData, new AuthenticatedData(origInfo, // OriginatorInfo
                auth.getRecipientInfos(), // ASN1Set
                auth.getMacAlgorithm(), // macAlgorithm
                digAlg, // AlgorithmIdentifier se les ha olvidado a BC implementar el getDigestAlgorithm
                auth.getEncapsulatedContentInfo(), // ContentInfo
                auth.getAuthAttrs(), // ASN1Set
                auth.getMac(), // ASN1OctetString
                auth.getUnauthAttrs() // ASN1Set
        )).getEncoded(ASN1Encoding.DER);
    }
    return null;
}