Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers envelopedData

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers envelopedData

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers envelopedData.

Prototype

ASN1ObjectIdentifier envelopedData

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers envelopedData.

Click Source Link

Document

PKCS#7: 1.2.840.113549.1.7.3

Usage

From source file:cljpdf.text.pdf.PdfPublicKeySecurityHandler.java

License:Mozilla Public License

private DERObject createDERForRecipient(byte[] in, X509Certificate cert)
        throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(
            algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    DERObject derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);//  w  w w .j a  v  a  2 s .  co  m
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data,
            algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.getDERObject();
}

From source file:com.itextpdf.kernel.crypto.securityhandler.PubKeySecurityHandler.java

License:Open Source License

private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
        throws IOException, GeneralSecurityException {
    EncryptionUtils.DERForRecipientParams parameters = EncryptionUtils.calculateDERForRecipientParams(in);

    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, parameters.abyte0);
    DEROctetString deroctetstring = new DEROctetString(parameters.abyte1);
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data,
            parameters.algorithmIdentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, (ASN1Set) null);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();
}

From source file:com.itextpdf.text.pdf.PdfPublicKeySecurityHandler.java

License:Open Source License

private ASN1Primitive createDERForRecipient(byte[] in, X509Certificate cert)
        throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(
            algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    ASN1Primitive derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);//from   w w  w. j av  a 2  s  .  c o m
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new ASN1ObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data,
            algorithmidentifier, deroctetstring);
    ASN1Set set = null;
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, set);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.toASN1Primitive();
}

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

License:Open Source License

/**
 * Método principal que obtiene la información a partir de un fichero firmado
 * de tipo CMS./*from  ww w .j ava 2 s  .co m*/
 * @param data Objeto CMS.
 * @return Texto descriptivo del objeto CMS.
 * @throws IOException Si ocurre algún problema leyendo o escribiendo los datos
 * @throws AOInvalidFormatException Error de formato no vá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.CAdESEnvelopedData.java

License:Open Source License

/** M&eacute;todo que genera la firma de tipo EnvelopedData.
 * @param parameters//from w  w  w .j av a  2s.c o  m
 *        Par&aacute;metros necesarios para la generaci&oacute;n de este
 *        tipo.
 * @param config
 *        Configuraci&oacute;n del algoritmo para firmar
 * @param certDest
 *        Certificado del destino al cual va dirigido la firma.
 * @param dataType
 *        Identifica el tipo del contenido a firmar.
 * @return la firma de tipo 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 java.security.NoSuchAlgorithmException
 *         Si no se soporta alguno de los algoritmos de firma o huella
 *         digital */
byte[] genEnvelopedData(final P7ContentSignerParameters parameters,
        final X509Certificate[] signerCertificateChain, final AOCipherConfig config,
        final X509Certificate[] certDest, final String dataType)
        throws IOException, CertificateEncodingException, NoSuchAlgorithmException {

    this.cipherKey = CAdESUtils.initEnvelopedData(config, certDest);

    // Datos previos &uacute;tiles
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(parameters.getSignatureAlgorithm());

    // 1. ORIGINATORINFO
    // obtenemos la lista de certificados
    final ASN1Set certificates = CAdESUtils.fetchCertificatesList(signerCertificateChain);
    final ASN1Set certrevlist = null;

    OriginatorInfo origInfo = null;
    if (signerCertificateChain.length != 0) {
        origInfo = new OriginatorInfo(certificates, certrevlist);
    }

    // 2. RECIPIENTINFOS
    final Info infos = CAdESUtils.getEnvelopeInfo(parameters.getContent(), config, certDest, this.cipherKey);

    // 3. ATRIBUTOS
    final ASN1Set unprotectedAttrs = SigUtils.getAttributeSet(new AttributeTable(
            CAdESUtils.initContexExpecific(digestAlgorithm, parameters.getContent(), dataType, null)));

    // construimos el Enveloped Data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo,
            new DERSet(infos.getRecipientInfos()), infos.getEncInfo(), unprotectedAttrs))
                    .getEncoded(ASN1Encoding.DER);

}

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

License:Open Source License

/** M&eacute;todo que genera la firma de tipo EnvelopedData.
 * @param data//from w  w w  .  ja  va2 s  .  com
 *        Datos binarios a firmar
 * @param digestAlg
 *        Algoritmo de hash
 * @param config
 *        Configuraci&oacute;n del algoritmo para firmar
 * @param certDest
 *        Certificado del destino al cual va dirigido la firma.
 * @param dataType
 *        Identifica el tipo del contenido a firmar.
 * @return la firma de tipo EnvelopedData.
 * @throws java.io.IOException
 *         Si hay problemas en la lectura de datos
 * @throws java.security.cert.CertificateEncodingException
 *         Cuando el certificado proporcionado no est&aacute; codificado
 *         adecuadamente
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se soporta alguno de los algoritmos indicados */
byte[] genEnvelopedData(final byte[] data, final String digestAlg, final AOCipherConfig config,
        final X509Certificate[] certDest, final String dataType)
        throws IOException, CertificateEncodingException, NoSuchAlgorithmException {
    this.cipherKey = CAdESUtils.initEnvelopedData(config, certDest);

    // Datos previos &uacute;tiles
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(digestAlg);

    // 1. ORIGINATORINFO
    final OriginatorInfo origInfo = null;

    // 2. RECIPIENTINFOS
    final Info infos = CAdESUtils.getEnvelopeInfo(data, config, certDest, this.cipherKey);

    // 3. ATRIBUTOS
    final ASN1Set unprotectedAttrs = SigUtils.getAttributeSet(
            new AttributeTable(CAdESUtils.initContexExpecific(digestAlgorithm, data, dataType, null)));

    // construimos el Enveloped Data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo,
            new DERSet(infos.getRecipientInfos()), infos.getEncInfo(), unprotectedAttrs))
                    .getEncoded(ASN1Encoding.DER);
}

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 2  s.co 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 www.jav a2 s  .c  o  m
 *        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.CMSEnvelopedData.java

License:Open Source License

/** Genera una estructura PKCS#7 <code>EnvelopedData</code>.
 * @param parameters Par&aacute;metros necesarios para la generaci&oacute;n de este
 *                   tipo./* w w  w .j  av a  2 s .  co m*/
 * @param signerCertificateChain Cadena de certificados del firmante.
 * @param config Configuraci&oacute;n del algoritmo para firmar
 * @param certDest Certificado del destino al cual va dirigido la firma.
 * @param dataType Identifica el tipo del contenido a firmar.
 * @param uatrib Conjunto de atributos no firmados.
 * @param keySize Tama&ntilde;o de la clave AES.
 * @return la firma de tipo 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 java.security.NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de firma o huella
 *                                                digital
 * @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.
 * @throws NoSuchPaddingException Cuando no se soporta un tipo de relleno necesario.
 * @throws InvalidKeyException Cuando hay problemas de adecuaci&oacute;n de la clave. */
byte[] genEnvelopedData(final P7ContentSignerParameters parameters,
        final X509Certificate[] signerCertificateChain, final AOCipherConfig config,
        final X509Certificate[] certDest, final String dataType, final Map<String, byte[]> uatrib,
        final Integer keySize) throws IOException, CertificateEncodingException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {

    this.cipherKey = Utils.initEnvelopedData(config, keySize);

    // Ya que el contenido puede ser grande, lo recuperamos solo una vez
    final byte[] content2 = parameters.getContent();

    // Datos previos &uacute;tiles
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(parameters.getSignatureAlgorithm());

    // 1. ORIGINATORINFO
    // obtenemos la lista de certificados
    final ASN1Set certificates = Utils.fetchCertificatesList(signerCertificateChain);
    final ASN1Set certrevlist = null;

    OriginatorInfo origInfo = null;
    if (signerCertificateChain.length != 0) {
        origInfo = new OriginatorInfo(certificates, certrevlist);
    }

    // 2. RECIPIENTINFOS
    final Info infos = Utils.initVariables(content2, config, certDest, this.cipherKey);

    // 4. ATRIBUTOS
    final ASN1Set unprotectedAttrs = Utils.generateSignerInfo(digestAlgorithm, content2, dataType, uatrib);

    // construimos el Enveloped Data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo,
            new DERSet(infos.getRecipientInfos()), infos.getEncInfo(), unprotectedAttrs))
                    .getEncoded(ASN1Encoding.DER);
}

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

License:Open Source License

/** Genera una estructura PKCS#7 <code>EnvelopedData</code>.
 * @param data Datos binarios a firmar.//from w  w  w.  java  2 s .  com
 * @param digestAlg Algoritmo de huella digital.
 * @param config Configuraci&oacute;n del algoritmo para firmar.
 * @param certDest Certificado del destino al cual va dirigido la firma.
 * @param dataType Identifica el tipo del contenido a firmar.
 * @param uatrib Conjunto de atributos no firmados.
 * @param keySize Tama&ntilde;o de la clave AES.
 * @return la firma de tipo EnvelopedData.
 * @throws java.io.IOException En caso de error en la lectura o tratamiento de datos
 * @throws java.security.cert.CertificateEncodingException Cuando hay problemas relacionados con la
 *                                                         codificaci&oacute;n de los certificados X.509.
 * @throws java.security.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.
 * @throws NoSuchPaddingException Cuando no se soporta un tipo de relleno necesario.
 * @throws InvalidKeyException Cuando hay problemas de adecuaci&oacute;n de la clave. */
byte[] genEnvelopedData(final byte[] data, final String digestAlg, final AOCipherConfig config,
        final X509Certificate[] certDest, final String dataType, final Map<String, byte[]> uatrib,
        final Integer keySize) throws IOException, CertificateEncodingException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {

    this.cipherKey = Utils.initEnvelopedData(config, keySize);

    // Datos previos utiles
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(digestAlg);

    // 1. ORIGINATORINFO
    final OriginatorInfo origInfo = null;

    // 2. RECIPIENTINFOS
    final Info infos = Utils.initVariables(data, config, certDest, this.cipherKey);

    // 4. ATRIBUTOS
    final ASN1Set unprotectedAttrs = Utils.generateSignerInfo(digestAlgorithm, data, dataType, uatrib);

    // construimos el Enveloped Data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.envelopedData, new EnvelopedData(origInfo,
            new DERSet(infos.getRecipientInfos()), infos.getEncInfo(), unprotectedAttrs))
                    .getEncoded(ASN1Encoding.DER);

}