Example usage for org.bouncycastle.asn1.cms AuthenticatedData getMac

List of usage examples for org.bouncycastle.asn1.cms AuthenticatedData getMac

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.cms AuthenticatedData getMac.

Prototype

public ASN1OctetString getMac() 

Source Link

Usage

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

License:Open Source License

/** Método que inserta remitentes en el "OriginatorInfo" de un sobre
 * de tipo AuthenticatedData.//from  w w  w .  j a  va 2s  . co  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í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;
}

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

License:Open Source License

/** Descifra un PKCS#7 <code>AuthenticatedData</code>.
 * @param cmsData Datos del tipo EnvelopedData.
 * @param keyEntry Clave privada del certificado usado para descifrar el
 *                 contenido//from w w  w. ja  v a  2  s  .c o m
 * @return El contenido de una firma de tipo authenticatedData.
 * @throws IOException Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *                     datos
 * @throws 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 NoSuchAlgorithmException Cuando no se reconozca el algoritmo utilizado para generar el
 *                                  c&oacute;digo de autenticaci&oacute;n.
 * @throws NoSuchPaddingException Cuando no se soporta un tipo de relleno necesario. */
byte[] decipherAuthenticatedData(final byte[] cmsData, final PrivateKeyEntry keyEntry)
        throws IOException, CertificateEncodingException, AOException, InvalidKeyException,
        NoSuchAlgorithmException, NoSuchPaddingException {
    byte[] contenido = new byte[0];

    AuthenticatedData authenticated = null;

    final Enumeration<?> elementRecipient;
    try {
        final ASN1Sequence authenticatedData = Utils.fetchWrappedData(cmsData);

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

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

    // Asignamos la clave de descifrado del contenido.
    assignKey(encryptedKeyDatas.getEncryptedKey(), keyEntry, encryptedKeyDatas.getAlgEncryptedKey());

    final ASN1Set authAttr = authenticated.getAuthAttrs();

    final byte[] macGenerada = Utils.genMac(this.macAlgorithmConfig.getName(),
            authAttr.getEncoded(ASN1Encoding.DER), this.cipherKey);

    final byte[] macObtenida = authenticated.getMac().getOctets();

    if (java.util.Arrays.equals(macGenerada, macObtenida)) {
        contenido = ((DEROctetString) authenticated.getEncapsulatedContentInfo().getContent()).getOctets();
    }

    return contenido;
}