Example usage for org.bouncycastle.asn1 ASN1Set getEncoded

List of usage examples for org.bouncycastle.asn1 ASN1Set getEncoded

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Set getEncoded.

Prototype

public byte[] getEncoded(String encoding) throws IOException 

Source Link

Document

Return either the default for "BER" or a DER encoding if "DER" is specified.

Usage

From source file:com.guardtime.asn1.SignedData.java

License:Apache License

/**
 * Class constructor./*ww  w  . j a va  2  s.  c  o m*/
 *
 * @param obj ASN.1 representation of signed data.
 *
 * @throws Asn1FormatException if provided ASN.1 object has invalid format.
 */
SignedData(ASN1Encodable obj) throws Asn1FormatException {
    try {
        signedData = org.bouncycastle.asn1.cms.SignedData.getInstance(obj);

        // Extract and check version
        //
        // RFC 2630/3161 require version to be 0..4
        // GuardTime requires version to be exactly 3
        BigInteger ver = signedData.getVersion().getValue();
        if (!ver.equals(BigInteger.valueOf(VERSION))) {
            throw new Asn1FormatException("invalid signed data version: " + ver);
        }
        version = ver.intValue();

        // Extract and check digest algorithm list
        //
        // Digest algorithm list can contain duplicate entries as
        // RFC 2630 does not directly deny that
        //
        // RFC 2630 allows digest algorithm list to be empty
        digestAlgorithms = new ArrayList();
        Enumeration e = signedData.getDigestAlgorithms().getObjects();
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            String algOid = AlgorithmIdentifier.getInstance(o).getAlgorithm().getId();
            Asn1Util.checkDigestAlgorithm(algOid);
            digestAlgorithms.add(algOid);
        }

        // Extract and check encapsulated content info
        ContentInfo eContentInfo = signedData.getEncapContentInfo();
        eContentType = eContentInfo.getContentType().toString();
        // RFC3161 requires type to be id-ct-TSTInfo
        if (!eContentType.equals(E_CONTENT_TYPE)) {
            throw new Asn1FormatException("invalid encapsulated content type: " + eContentType);
        }
        DEROctetString eContentData = (DEROctetString) eContentInfo.getContent();
        eContent = TstInfo.getInstance(eContentData.getOctetStream());

        // Extract certificates (optional field)
        ASN1Set certificates = signedData.getCertificates();
        if (certificates != null && certificates.size() > 0) {
            byte[] certBytes = certificates.getObjectAt(0).toASN1Primitive().getEncoded(ASN1Encoding.DER);
            InputStream in = new ByteArrayInputStream(certBytes);
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            certificate = (X509Certificate) cf.generateCertificate(in);
        }

        // Extract CRLs (GuardTime is not currently using CRLs field)
        ASN1Set rawCrls = signedData.getCRLs();
        crls = ((rawCrls == null) ? null : rawCrls.getEncoded(ASN1Encoding.DER));

        // Extract and check signer info
        ASN1Set signerInfos = signedData.getSignerInfos();
        // RFC 3161 requires signer info list to contain exactly one entry
        if (signerInfos.size() != 1) {
            throw new Asn1FormatException("wrong number of signer infos found: " + signerInfos.size());
        }
        signerInfo = new SignerInfo(signerInfos.getObjectAt(0).toASN1Primitive());
        // Make sure digest algorithm is contained in digest algorithm list
        // TODO: check disabled as this problem is not critical.
        //String digestAlgorithmOid = signerInfo.getDigestAlgorithm();
        //if (!digestAlgorithms.contains(digestAlgorithmOid)) {
        //   throw new Asn1FormatException("digest algorithm not found in list: " + digestAlgorithmOid);
        //}
    } catch (Asn1FormatException e) {
        throw e;
    } catch (Exception e) {
        // Also catches IllegalArgumentException, NullPointerException, etc.
        throw new Asn1FormatException("signed data has invalid format", e);
    }
}

From source file:com.guardtime.asn1.SignerInfo.java

License:Apache License

/**
 * Class constructor./*w w w  .j a v a 2 s.c  o  m*/
 *
 * @param obj ASN.1 representation of signer info.
 *
 * @throws Asn1FormatException if provided ASN.1 object has invalid format.
 */
SignerInfo(ASN1Encodable obj) throws Asn1FormatException {
    try {
        signerInfo = org.bouncycastle.asn1.cms.SignerInfo.getInstance(obj);

        // Extract and check version
        //
        // Since we use the IssuerAndSerialNumber option to identify the
        // signer's certificate, the version has to be 1.
        BigInteger ver = signerInfo.getVersion().getValue();
        if (!ver.equals(BigInteger.valueOf(VERSION))) {
            throw new Asn1FormatException("invalid signer info version: " + ver);
        }
        version = ver.intValue();

        // Extract the signer's certificate identification
        IssuerAndSerialNumber sid = IssuerAndSerialNumber.getInstance(signerInfo.getSID().toASN1Primitive());
        issuerName = sid.getName().toString();
        serialNumber = sid.getSerialNumber().getValue();

        // Extract the digest algorithm ID
        digestAlgorithm = signerInfo.getDigestAlgorithm().getAlgorithm().getId();
        Asn1Util.checkDigestAlgorithm(digestAlgorithm);

        // Extract and check the signed attributes
        //
        // The content-type and message-digest attributes must be present.
        ASN1Set sigAttrs = signerInfo.getAuthenticatedAttributes();
        if (sigAttrs == null) {
            throw new Asn1FormatException("no signed attributes");
        }
        ASN1Encodable ct = Asn1Util.getAttributeValue(sigAttrs, CONTENT_TYPE_ID);
        if (ct == null || !ct.equals(new ASN1ObjectIdentifier(CONTENT_TYPE))) {
            throw new Asn1FormatException("invalid content-type signed attribute value");
        }
        ASN1Encodable md = Asn1Util.getAttributeValue(sigAttrs, MESSAGE_DIGEST_ID);
        if (md == null || !(md instanceof DEROctetString)) {
            throw new Asn1FormatException("invalid message-digest signed attribute");
        }
        messageDigest = ((ASN1OctetString) md).getOctets();
        signedAttrs = sigAttrs.getEncoded(ASN1Encoding.DER);

        // Extract and check the signature algorithm ID
        signatureAlgorithm = signerInfo.getDigestEncryptionAlgorithm().getAlgorithm().getId();
        if (!signatureAlgorithm.equals(SIGNATURE_ALGORITHM)) {
            throw new Asn1FormatException("invalid signature algorithm: " + signatureAlgorithm);
        }

        // Extract the signature
        signature = new TimeSignature(ASN1Primitive.fromByteArray(signerInfo.getEncryptedDigest().getOctets()));

        // Extract the unsigned attributes
        ASN1Set unsigAttrs = signerInfo.getUnauthenticatedAttributes();
        unsignedAttrs = ((unsigAttrs == null) ? null : unsigAttrs.getEncoded(ASN1Encoding.DER));
    } catch (Asn1FormatException e) {
        throw e;
    } catch (Exception e) {
        // Also catches IllegalArgumentException, NullPointerException, etc.
        throw new Asn1FormatException("signer info has invalid format", e);
    }
}

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

License:Open Source License

/**
 * Verifies a signature using the sub-filter adbe.pkcs7.detached or
 * adbe.pkcs7.sha1./*from w w w . j  a  v  a  2s .c  o  m*/
 * @param contentsKey the /Contents key
 * @param provider the provider or <code>null</code> for the default provider
 */
@SuppressWarnings("unchecked")
public PdfPKCS7(byte[] contentsKey, String provider) {
    try {
        this.provider = provider;
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey));

        //
        // Basic checks to make sure it's a PKCS#7 SignedData Object
        //
        DERObject pkcs;

        try {
            pkcs = din.readObject();
        } catch (IOException e) {
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object"));
        }
        if (!(pkcs instanceof ASN1Sequence)) {
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
        }
        ASN1Sequence signedData = (ASN1Sequence) pkcs;
        DERObjectIdentifier objId = (DERObjectIdentifier) signedData.getObjectAt(0);
        if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA))
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
        ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) signedData.getObjectAt(1)).getObject();
        // the positions that we care are:
        //     0 - version
        //     1 - digestAlgorithms
        //     2 - possible ID_PKCS7_DATA
        //     (the certificates and crls are taken out by other means)
        //     last - signerInfos

        // the version
        version = ((DERInteger) content.getObjectAt(0)).getValue().intValue();

        // the digestAlgorithms
        digestalgos = new HashSet<String>();
        Enumeration<ASN1Sequence> e = ((ASN1Set) content.getObjectAt(1)).getObjects();
        while (e.hasMoreElements()) {
            ASN1Sequence s = e.nextElement();
            DERObjectIdentifier o = (DERObjectIdentifier) s.getObjectAt(0);
            digestalgos.add(o.getId());
        }

        // the certificates
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(contentsKey));
        certs = cr.engineReadAll();

        // the possible ID_PKCS7_DATA
        ASN1Sequence rsaData = (ASN1Sequence) content.getObjectAt(2);
        if (rsaData.size() > 1) {
            DEROctetString rsaDataContent = (DEROctetString) ((DERTaggedObject) rsaData.getObjectAt(1))
                    .getObject();
            RSAdata = rsaDataContent.getOctets();
        }

        // the signerInfos
        int next = 3;
        while (content.getObjectAt(next) instanceof DERTaggedObject)
            ++next;
        ASN1Set signerInfos = (ASN1Set) content.getObjectAt(next);
        if (signerInfos.size() != 1)
            throw new IllegalArgumentException(MessageLocalization.getComposedMessage(
                    "this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
        ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0);
        // the positions that we care are
        //     0 - version
        //     1 - the signing certificate issuer and serial number
        //     2 - the digest algorithm
        //     3 or 4 - digestEncryptionAlgorithm
        //     4 or 5 - encryptedDigest
        signerversion = ((DERInteger) signerInfo.getObjectAt(0)).getValue().intValue();
        // Get the signing certificate
        ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1);
        X509Principal issuer = new X509Principal(
                issuerAndSerialNumber.getObjectAt(0).getDERObject().getEncoded());
        BigInteger serialNumber = ((DERInteger) issuerAndSerialNumber.getObjectAt(1)).getValue();
        for (Object element : certs) {
            X509Certificate cert = (X509Certificate) element;
            if (issuer.equals(cert.getIssuerDN()) && serialNumber.equals(cert.getSerialNumber())) {
                signCert = cert;
                break;
            }
        }
        if (signCert == null) {
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("can.t.find.signing.certificate.with.serial.1",
                            issuer.getName() + " / " + serialNumber.toString(16)));
        }
        signCertificateChain();
        digestAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0))
                .getId();
        next = 3;
        if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
            ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next);
            ASN1Set sseq = ASN1Set.getInstance(tagsig, false);
            sigAttr = sseq.getEncoded(ASN1Encodable.DER);

            for (int k = 0; k < sseq.size(); ++k) {
                ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k);
                if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) {
                    ASN1Set set = (ASN1Set) seq2.getObjectAt(1);
                    digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets();
                } else if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_ADBE_REVOCATION)) {
                    ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
                    ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
                    for (int j = 0; j < seqout.size(); ++j) {
                        ASN1TaggedObject tg = (ASN1TaggedObject) seqout.getObjectAt(j);
                        if (tg.getTagNo() == 0) {
                            ASN1Sequence seqin = (ASN1Sequence) tg.getObject();
                            findCRL(seqin);
                        }
                        if (tg.getTagNo() == 1) {
                            ASN1Sequence seqin = (ASN1Sequence) tg.getObject();
                            findOcsp(seqin);
                        }
                    }
                }
            }
            if (digestAttr == null)
                throw new IllegalArgumentException(MessageLocalization
                        .getComposedMessage("authenticated.attribute.is.missing.the.digest"));
            ++next;
        }
        digestEncryptionAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++))
                .getObjectAt(0)).getId();
        digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets();
        if (next < signerInfo.size() && signerInfo.getObjectAt(next) instanceof DERTaggedObject) {
            DERTaggedObject taggedObject = (DERTaggedObject) signerInfo.getObjectAt(next);
            ASN1Set unat = ASN1Set.getInstance(taggedObject, false);
            AttributeTable attble = new AttributeTable(unat);
            Attribute ts = attble.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
            if (ts != null && ts.getAttrValues().size() > 0) {
                ASN1Set attributeValues = ts.getAttrValues();
                ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0));
                ContentInfo contentInfo = new ContentInfo(tokenSequence);
                this.timeStampToken = new TimeStampToken(contentInfo);
            }
        }
        if (RSAdata != null || digestAttr != null) {
            if (provider == null || provider.startsWith("SunPKCS11"))
                messageDigest = MessageDigest.getInstance(getHashAlgorithm());
            else
                messageDigest = MessageDigest.getInstance(getHashAlgorithm(), provider);
        }
        if (provider == null)
            sig = Signature.getInstance(getDigestAlgorithm());
        else
            sig = Signature.getInstance(getDigestAlgorithm(), provider);
        sig.initVerify(signCert.getPublicKey());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

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

License:Open Source License

/** Obtiene la estructura ASN.1 de firma usando los atributos del firmante.
 * @param signatureAlgorithm//from  w  w w.  j av  a 2s  .  c o  m
 *        Algoritmo para la firma
 * @param keyEntry
 *        Clave para firmar.
 * @param signedAttr2
 *        Atributos firmados
 * @return Firma de los atributos.
 * @throws AOException
 *         si ocurre cualquier error durante la firma */
static ASN1OctetString firma(final String signatureAlgorithm, final PrivateKeyEntry keyEntry,
        final ASN1Set signedAttr2) throws AOException {

    final Signature sig;
    try {
        sig = Signature.getInstance(signatureAlgorithm);
    } catch (final Exception e) {
        throw new AOException("Error obteniendo la clase de firma para el algoritmo " + signatureAlgorithm, e); //$NON-NLS-1$
    }

    final byte[] tmp;
    try {
        tmp = signedAttr2.getEncoded(ASN1Encoding.DER);
    } catch (final IOException ex) {
        throw new AOException("Error obteniendo el contenido a firmar", ex); //$NON-NLS-1$
    }

    // Indicar clave privada para la firma
    try {
        sig.initSign(keyEntry.getPrivateKey());
    } catch (final Exception e) {
        throw new AOException("Error al inicializar la firma con la clave privada", e); //$NON-NLS-1$
    }

    // Actualizamos la configuracion de firma
    try {
        sig.update(tmp);
    } catch (final SignatureException e) {
        throw new AOException("Error al configurar la informacion de firma", e); //$NON-NLS-1$
    }

    // firmamos.
    final byte[] realSig;
    try {
        realSig = sig.sign();
    } catch (final Exception e) {
        throw new AOException("Error durante el proceso de firma", e); //$NON-NLS-1$
    }

    return new DEROctetString(realSig);
}

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//from w ww.j  a  v a  2  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.CMSAuthenticatedEnvelopedData.java

License:Open Source License

/** Genera una estructura PKCS#7 <code>AuthenticatedEnvelopedData</code>.
 * @param parameters Par&aacute;metros necesarios que contienen tanto la firma del
 *                   archivo a firmar como los datos del firmante.
 * @param signerCertificateChain Cadena de certificados del firmante.
 * @param autenticationAlgorithm Algoritmo de autenticacion
 * @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 applySigningTime Si se aplica la hora de firma 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//from   w w  w. java  2 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[] genAuthenticatedEnvelopedData(final P7ContentSignerParameters parameters,
        final X509Certificate[] signerCertificateChain, final String autenticationAlgorithm,
        final AOCipherConfig config, final X509Certificate[] certDest, final String dataType,
        final boolean applySigningTime, 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(signerCertificateChain);
    ASN1Set certrevlist = null;

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

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

    // 4. ATRIBUTOS FIRMADOS
    final ASN1Set authAttr = generateSignedAtt(dataType, applySigningTime, atrib);

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

    // 6. ATRIBUTOS NO FIRMADOS.
    final ASN1Set unAuthAttr = Utils.generateUnsignedAtt(uatrib);

    // construimos el Authenticated data y lo devolvemos
    return new ContentInfo(PKCSObjectIdentifiers.id_ct_authEnvelopedData, new AuthEnvelopedData(origInfo, // originatorInfo,
            new DERSet(infos.getRecipientInfos()), // recipientInfos,
            infos.getEncInfo(), // authEncryptedContentInfo,
            authAttr, // authAttrs
            new DEROctetString(mac), // MAC
            unAuthAttr // unauthAttrs
    )).getEncoded(ASN1Encoding.DER);

}

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/* w w w.j a v  a 2  s.  c om*/
 * @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;
}

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

License:Open Source License

/** Obtiene la estructura ASN.1 de firma usando los atributos del firmante.
 * @param signatureAlgorithm Algoritmo para la firma.
 * @param keyEntry Clave para firmar./*from   ww  w  .jav  a 2 s  .  c o  m*/
 * @param signedAttr2 Atributos firmados.
 * @return Firma de los atributos.
 * @throws NoSuchAlgorithmException Cuando el JRE no soporta alg&uacute;n algoritmo necesario.
 * @throws IOException Cuando hay problemas de entrada / salida.
 * @throws InvalidKeyException Cuando la clave proporcionada no es v&aacute;lida.
 * @throws SignatureException Cuando hay problemas con la firma PKCS#1. */
static ASN1OctetString firma(final String signatureAlgorithm, final PrivateKeyEntry keyEntry,
        final ASN1Set signedAttr2)
        throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException {

    final Signature sig = Signature.getInstance(signatureAlgorithm);

    final byte[] tmp = signedAttr2.getEncoded(ASN1Encoding.DER);

    // Indicar clave privada para la firma
    sig.initSign(keyEntry.getPrivateKey());

    // Actualizamos la configuracion de firma
    if (tmp != null) {
        sig.update(tmp);
    }

    // firmamos.
    final byte[] realSig = sig.sign();

    return new DEROctetString(realSig);

}

From source file:es.gob.afirma.signers.cades.CAdESTriPhaseSigner.java

License:Open Source License

/** Genera los atributos firmados CAdES (prefirma).
 * @param digestAlgorithmName Algoritmo de huella digital
 * @param content Datos a firmar (usar <code>null</code> si no se desean a&ntilde;adir a la firma)
 * @param signerCertificateChain Cadena de certificados del firmante
 * @param policy Pol&iacute;tica de firma
 * @param signingCertificateV2 <code>true</code> para usar SigningCertificateV2, <code>false</code> para usar V1
 * @param dataDigest Valor de la huella digital del contenido (usar <code>null</code> si se estableci&oacute; <code>content</code>)
 * @param signDate Fecha de la firma (debe establecerse externamente para evitar desincronismos en la firma trif&aacute;sica)
 * @param padesMode <code>true</code> para generar una firma CAdES compatible PAdES, <code>false</code> para generar una firma CAdES normal
 * @param contentType Tipo de contenido definido por su OID.
 * @param contentDescription Descripci&oacute;n textual del tipo de contenido firmado.
 * @param ctis Indicaciones sobre los tipos de compromisos adquiridos con la firma.
 * @param csm Metadatos sobre el firmante.
 * @return Atributos CAdES a firmar (prefirma) en formato ASN.1
 * @throws AOException Cuando se produce cualquier error durante el proceso. */
public static byte[] preSign(final String digestAlgorithmName, final byte[] content,
        final java.security.cert.Certificate[] signerCertificateChain, final AdESPolicy policy,
        final boolean signingCertificateV2, final byte[] dataDigest, final Date signDate,
        final boolean padesMode, final String contentType, final String contentDescription,
        final List<CommitmentTypeIndicationBean> ctis, final CAdESSignerMetadata csm) throws AOException {

    if (signerCertificateChain == null || signerCertificateChain.length == 0) {
        throw new IllegalArgumentException("La cadena de certificados debe contener al menos una entrada"); //$NON-NLS-1$
    }/*from  w  ww  .  j a v a2s . c  o m*/

    // Atributos firmados
    final ASN1Set signedAttributes;
    try {
        signedAttributes = SigUtils
                .getAttributeSet(new AttributeTable(CAdESUtils.generateSignerInfo(signerCertificateChain[0],
                        digestAlgorithmName, content, policy, signingCertificateV2, dataDigest, signDate,
                        padesMode, contentType, contentDescription, ctis, csm)));
    } catch (final Exception e) {
        throw new AOException("Error obteniendo los atributos a firmar: " + e, e); //$NON-NLS-1$
    }

    try {
        return signedAttributes.getEncoded(ASN1Encoding.DER);
    } catch (final Exception ex) {
        throw new AOException("Error al codificar los datos ASN.1 a firmar finalmente", ex); //$NON-NLS-1$
    }

}

From source file:es.gob.afirma.signers.multi.cades.CAdESCounterSigner.java

License:Open Source License

/** Genera un signerInfo espec&iacute;fico utilizando los
 * datos necesarios para crearlo. Se utiliza siempre que no se sabe cual es
 * el signerInfo que se debe firmar.//from  w w w  . j a va2 s  .  c o m
 * @param signatureAlgorithm Algoritmo de firma a usar.
 * @param si SignerInfo del que se debe recoger la informaci&oacute;n para
 *           realizar la contrafirma espec&iacute;fica.
 * @param key Clave privada a usar para firmar.
 * @param certChain Cadena de certificados del firmante.
 * @param contentDescription Descripci&oacute;n textual del tipo de contenido firmado.
 * @param policy Pol&iacute;tica de firma.
 * @param signingCertificateV2 <code>true</code> si se desea usar <i>SigningCertificateV2</i>, <code>false</code>
 *        para usar <i>SigningCertificateV1</i>.
 * @param ctis Indicaciones sobre los tipos de compromisos adquiridos con la firma.
 * @param csm Metadatos sobre el firmante.
 * @return <i>SignerInfo</i> contrafirmado.
 * @throws NoSuchAlgorithmException Si no se soporta alguno de los algoritmos necesarios.
 * @throws java.io.IOException Cuando hay errores de entrada / salida
 * @throws CertificateException Cuando hay problemas con los certificados proporcionados. */
private SignerInfo generateSignerInfo(final String signatureAlgorithm, final SignerInfo si,
        final PrivateKey key, final java.security.cert.Certificate[] certChain, final String contentDescription,
        final AdESPolicy policy, final boolean signingCertificateV2,
        final List<CommitmentTypeIndicationBean> ctis, final CAdESSignerMetadata csm)
        throws NoSuchAlgorithmException, IOException, CertificateException {
    // buscamos que timo de algoritmo es y lo codificamos con su OID
    final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm);

    // authenticatedAttributes
    final ASN1EncodableVector contextExcepcific = CAdESUtils.generateSignerInfo(certChain[0], digestAlgorithm,
            si.getEncryptedDigest().getOctets(), policy, signingCertificateV2, null,
            this.date != null ? this.date : new Date(), // Usamos fecha y hora actual nueva si no se nos ha indicado otra distinta
            false, null, // En contrafirma el ContentType no se pone
            contentDescription, ctis, csm);

    final ASN1Set signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExcepcific));

    final ASN1OctetString sign2;
    try {
        sign2 = new DEROctetString(
                pkcs1Sign(signedAttr.getEncoded(ASN1Encoding.DER), signatureAlgorithm, key, certChain));
    } catch (final AOException ex) {
        throw new IOException("Error al realizar la firma: " + ex, ex); //$NON-NLS-1$
    }

    // AlgorithmIdentifier
    final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm));

    // digEncryptionAlgorithm
    final AlgorithmIdentifier encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$

    // 5. SIGNERINFO
    // raiz de la secuencia de SignerInfo
    final TBSCertificateStructure tbs = TBSCertificateStructure
            .getInstance(ASN1Primitive.fromByteArray(((X509Certificate) certChain[0]).getTBSCertificate()));
    final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()),
            tbs.getSerialNumber().getValue());
    final SignerIdentifier identifier = new SignerIdentifier(encSid);

    // UNAUTHENTICATEDATTRIBUTES
    final ASN1Set unsignedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExcepcific));

    return new SignerInfo(identifier, digAlgId, unsignedAttr, encAlgId, sign2, null);

}