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

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

Introduction

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

Prototype

ASN1ObjectIdentifier id_ct_authData

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

Click Source Link

Document

PKCS#9: 1.2.840.113549.1.9.16.1.2 -- smime ct authData

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  ww w.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.cms.CMSAuthenticatedData.java

License:Open Source License

/** Genera una estructura PKCS#7 <code>AuthenticatedData</code>.
 * @param parameters Par&aacute;metros necesarios que contienen tanto la firma del
 *                    archivo a firmar como los datos del firmante.
 * @param signerCertChain Cadena de certificados del firmante.
 * @param autenticationAlgorithm Algoritmo para los codigos de autenticaci&oacute;n MAC
 * @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 applyTimestamp Si se aplica el Timestamp o no.
 * @param atrib Atributos firmados opcionales.
 * @param uatrib Atributos no autenticados firmados opcionales.
 * @param keySize Tama&ntilde;o de la clave AES.
 * @return Firma de tipo AuthenticatedData.
 * @throws IOException Si ocurre alg&uacute;n problema leyendo o escribiendo los
 *                     datos/* w w  w . j  a  v a2 s .c o m*/
 * @throws CertificateEncodingException Si se produce alguna excepci&oacute;n con los certificados de
 *                                      firma.
 * @throws NoSuchAlgorithmException Si no se encuentra un algoritmo v&aacute;lido.
 * @throws InvalidKeyException Cuando hay problemas de adecuaci&oacute;n de la clave.
 * @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. */
static byte[] genAuthenticatedData(final P7ContentSignerParameters parameters,
        final X509Certificate[] signerCertChain, final String autenticationAlgorithm,
        final AOCipherConfig config, final X509Certificate[] certDest, final String dataType,
        final boolean applyTimestamp, final Map<String, byte[]> atrib, final Map<String, byte[]> uatrib,
        final Integer keySize) throws IOException, CertificateEncodingException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {

    final SecretKey cipherKey = Utils.initEnvelopedData(config, keySize);

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

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

    OriginatorInfo origInfo = null;
    if (signerCertChain.length != 0) {
        // introducimos una lista vacia en los CRL ya que no podemos
        // modificar el codigo de bc.
        final List<ASN1Encodable> crl = new ArrayList<ASN1Encodable>();
        certrevlist = SigUtils.createBerSetFromList(crl);
        origInfo = new OriginatorInfo(certificates, certrevlist);
    }

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

    // 3. MACALGORITHM
    final AlgorithmIdentifier macAlgorithm = SigUtils.makeAlgId(config.getAlgorithm().getOid());

    // 4. DIGESTALGORITMIDENTIFIER
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(parameters.getSignatureAlgorithm());
    final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));

    // 5. ENCAPSULATEDCONTENTINFO

    // si se introduce el contenido o no

    ContentInfo encInfo = null;
    final ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(dataType);
    final ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    final CMSProcessable msg = new CMSProcessableByteArray(content2);
    try {
        msg.write(bOut);
    } catch (final CMSException ex) {
        throw new IOException("Error en la escritura del procesable CMS: " + ex, ex); //$NON-NLS-1$
    }
    encInfo = new ContentInfo(contentTypeOID, new BEROctetString(bOut.toByteArray()));

    // 6. ATRIBUTOS FIRMADOS
    ASN1Set authAttr = null;
    authAttr = generateSignedAtt(signerCertChain[0], digestAlgorithm, content2, dataType, applyTimestamp,
            atrib);

    // 7. MAC
    final byte[] mac = Utils.genMac(autenticationAlgorithm, authAttr.getEncoded(ASN1Encoding.DER), cipherKey);

    // 8. ATRIBUTOS NO FIRMADOS.

    ASN1Set unAuthAttr = null;
    unAuthAttr = Utils.generateUnsignedAtt(uatrib);

    // construimos el Authenticated data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.id_ct_authData, new AuthenticatedData(origInfo, // OriginatorInfo
            new DERSet(infos.getRecipientInfos()), // ASN1Set
            macAlgorithm, // macAlgorithm
            digAlgId, // AlgorithmIdentifier
            encInfo, // ContentInfo
            authAttr, // ASN1Set
            new DEROctetString(mac), // ASN1OctetString
            unAuthAttr // ASN1Set
    )).getEncoded(ASN1Encoding.DER);

}

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.// w  w  w.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;
}

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 "AuthenticatedData"
 * @param data/* www  .  j a  v  a 2  s.  com*/
 *        Datos CMS.
 * @return si es de este tipo. */
static boolean isCMSAuthenticatedData(final byte[] data) {
    boolean isValid = true;

    try {
        // Leemos el fichero que contiene la firma.
        final ASN1InputStream is = new ASN1InputStream(data);
        // Comenzamos a obtener los datos.
        final ASN1Sequence dsq = (ASN1Sequence) is.readObject();
        is.close();
        final Enumeration<?> e = dsq.getObjects();
        // Elementos que contienen los elementos OID AuthenticatedData.
        final ASN1ObjectIdentifier doi = (ASN1ObjectIdentifier) e.nextElement();
        if (!doi.equals(PKCSObjectIdentifiers.id_ct_authData)) {
            isValid = false;
        } else {
            // Contenido de AuthenticatedData
            final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement();
            final ASN1Sequence authenticatedData = (ASN1Sequence) doj.getObject();
            AuthenticatedData.getInstance(authenticatedData);
        }
    } catch (final Exception ex) {
        isValid = false;
    }
    return isValid;
}