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

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

Introduction

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

Prototype

ASN1ObjectIdentifier digestedData

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

Click Source Link

Document

PKCS#7: 1.2.840.113549.1.7.5

Usage

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   www  .j  a  va 2s  . c  o  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.CAdESDigestedData.java

License:Open Source License

/** M&eacute;todo que genera la firma de tipo digestedData.
 * @param parameters//www  . jav a  2 s. c  o m
 *        Par&aacute;metros necesarios para la generaci&oacute;n de este
 *        tipo.
 * @param dataType
 *        Identifica el tipo del contenido a firmar.
 * @return Mensaje firmado en tipo Digested Data.
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se soporta alguno de los algoritmos de firma o huella
 *         digital
 * @throws java.io.IOException
 *         Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *         datos */
static byte[] genDigestedData(final P7ContentSignerParameters parameters, final String dataType)
        throws NoSuchAlgorithmException, IOException {
    if (parameters == null) {
        throw new IllegalArgumentException("Los parametros no pueden ser nulos"); //$NON-NLS-1$
    }
    // Obtenemos el algoritmo para "digestear"
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(parameters.getSignatureAlgorithm());
    final AlgorithmIdentifier digAlgId;
    try {
        digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));
    } catch (final Exception e) {
        throw new IOException(new StringBuilder().append("Error de codificacion: ").append(e).toString(), e); //$NON-NLS-1$
    }

    // indicamos el tipo de contenido
    final ContentInfo encInfo = new ContentInfo(new ASN1ObjectIdentifier(dataType), null);

    // digest
    final DEROctetString digest = new DEROctetString(
            MessageDigest.getInstance(digestAlgorithm).digest(parameters.getContent()));

    // construimos el digestedData.
    return new ContentInfo(PKCSObjectIdentifiers.digestedData, new DigestedData(digAlgId, encInfo, digest))
            .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.//from w w  w  .  ja v a 2  s . 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//  ww w  .j a v  a2  s  .c  om
 *        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.CMSDigestedData.java

License:Open Source License

/** Genera una estructura de tipo digestedData.
 * @param content//w ww  . j av  a  2 s  . c o m
 *        Contenido original
 * @param digestAlgorithm
 *        Algoritmo de huella digital (<i>digest</i>) a usar
 * @param dataType
 *        Identifica el tipo del contenido a firmar.
 * @return Mensaje firmado en tipo Digested Data.
 * @throws java.security.NoSuchAlgorithmException
 *         Si no se soporta alguno de los algoritmos de firma o huella
 *         digital
 * @throws java.io.IOException
 *         Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *         datos */
static byte[] genDigestedData(final byte[] content, final String digestAlgorithm, final String dataType)
        throws NoSuchAlgorithmException, IOException {

    // Obtenemos el algoritmo para hacer el digest
    final AlgorithmIdentifier digAlgId = SigUtils
            .makeAlgId(AOAlgorithmID.getOID(AOSignConstants.getDigestAlgorithmName(digestAlgorithm)));

    // indicamos el tipo de contenido
    final ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(dataType);
    final ContentInfo encInfo = new ContentInfo(contentTypeOID, null);

    // digest
    final DEROctetString digest = new DEROctetString(
            MessageDigest.getInstance(digestAlgorithm).digest(content));

    // construimos el digestedData.
    return new ContentInfo(PKCSObjectIdentifiers.digestedData, new DigestedData(digAlgId, encInfo, digest))
            .getEncoded(ASN1Encoding.DER);
}

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 "Digested data"
 * @param data/*from  ww  w .  j a v  a  2 s  .com*/
 *        Datos CMS.
 * @return si es de este tipo. */
@SuppressWarnings("unused")
static boolean isCMSDigestedData(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.digestedData)) {
            isValid = false;
        } else {
            // Contenido de Data
            final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

            /*
             * Estas variables no se usan, solo es para verificar que la
             * conversion ha sido correcta. De no ser asi, se pasaria al
             * manejo de la excepcion.
             */
            new DigestedData((ASN1Sequence) 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>DigestedData</i>.
 * @param data Datos PKCS#7/CMS/CAdES.//  w w  w.j  a  v  a  2s  .  c o  m
 * @return <code>true</code> si los datos proporcionados se corresponden con una estructura de tipo <i>DigestedData</i>,
 * <code>false</code> en caso contrario.
 * @throws IOException Si ocurren problemas relacionados con la lectura de los datos */
@SuppressWarnings("unused")
static boolean isCAdESDigestedData(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.digestedData)) {
        isValid = true;
    }
    // Contenido de Data
    final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();

    try {
        /* Los resultados no se usan, solo es para verificar que la
         * conversion ha sido correcta. De no ser asi, se pasaria al manejo
         * de la excepcion. */
        new DigestedData((ASN1Sequence) doj.getObject());

    } catch (final Exception ex) {
        LOGGER.info("Los datos proporcionados no son de tipo DigestedData: " + ex); //$NON-NLS-1$
        return false;
    }

    return isValid;
}