List of usage examples for org.bouncycastle.asn1.cms SignedData getEncapContentInfo
public ContentInfo getEncapContentInfo()
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") static protected SignedData includeCrls(byte[] assinatura, Collection crls) throws IOException, Exception, SecurityException, CRLException, NoSuchProviderException, NoSuchAlgorithmException { org.bouncycastle.asn1.pkcs.SignedData pkcs7 = pkcs7SignedData(assinatura); ContentInfo content = new ContentInfo(CMSObjectIdentifiers.data, null); SignedData signedCms = new SignedData(pkcs7.getDigestAlgorithms(), content, pkcs7.getCertificates(), pkcs7.getCRLs(), pkcs7.getSignerInfos()); ASN1EncodableVector vec = new ASN1EncodableVector(); for (X509CRLObject crl : (Collection<X509CRLObject>) crls) vec.add(ASN1Primitive.fromByteArray(crl.getEncoded())); DERSet set = new DERSet(vec); // for (X509CRLObject crl : (Collection<X509CRLObject>) crls) // set.addObject(ASN1Object.fromByteArray(crl.getEncoded())); SignedData signedCmsWithCrls = new SignedData(signedCms.getDigestAlgorithms(), signedCms.getEncapContentInfo(), signedCms.getCertificates(), set, signedCms.getSignerInfos()); signedCmsWithCrls.getCertificates(); signedCmsWithCrls.getCRLs();//w w w .ja v a2 s . c om return signedCmsWithCrls; }
From source file:com.guardtime.asn1.Asn1Util.java
License:Apache License
/** * Extends the given content info with data from the given certification * token.// w w w .j av a 2 s.c om * * @param contentInfo * the original timestamp encoded in a CMS {@code ContentInfo} * structure. * @param certToken * the {@code CertToken} from the GuardTime online verification * service. * @return updated (extended) timestamp encoded in a new CMS * {@code ContentInfo} structure. */ static org.bouncycastle.asn1.cms.ContentInfo extend(org.bouncycastle.asn1.cms.ContentInfo contentInfo, Asn1CertToken certToken) throws Asn1FormatException { ASN1EncodableVector v; // Extract signed data ASN1Encodable asn1SignedData = contentInfo.getContent(); org.bouncycastle.asn1.cms.SignedData content = org.bouncycastle.asn1.cms.SignedData .getInstance(asn1SignedData); // Extract signer info ASN1Encodable asn1SignerInfo = content.getSignerInfos().getObjectAt(0); org.bouncycastle.asn1.cms.SignerInfo signerInfo = org.bouncycastle.asn1.cms.SignerInfo .getInstance(asn1SignerInfo); // Extract time signature ASN1Primitive asn1TimeSignature = null; try { asn1TimeSignature = ASN1Primitive.fromByteArray(signerInfo.getEncryptedDigest().getOctets()); } catch (IOException e) { throw new Asn1FormatException("time signature has invalid format"); } Asn1TimeSignature timeSignature = Asn1TimeSignature.getInstance(asn1TimeSignature); // Extend TimeSignature v = new ASN1EncodableVector(); v.add(timeSignature.getLocation()); v.add(certToken.getHistory()); v.add(certToken.getPublishedData()); // Skip PK signature <- updated v.add(new DERTaggedObject(false, 1, certToken.getPubReference())); timeSignature = Asn1TimeSignature.getInstance(new DERSequence(v)); // Extend SignerInfo v = new ASN1EncodableVector(); v.add(signerInfo.getVersion()); v.add(signerInfo.getSID()); v.add(signerInfo.getDigestAlgorithm()); ASN1Set signedAttrs = signerInfo.getAuthenticatedAttributes(); if (signedAttrs != null) { v.add(new DERTaggedObject(false, 0, signedAttrs)); } v.add(signerInfo.getDigestEncryptionAlgorithm()); try { v.add(new DEROctetString(timeSignature)); // <- updated } catch (IOException e) { throw new Asn1FormatException(e); } ASN1Set unsignedAttrs = signerInfo.getUnauthenticatedAttributes(); if (unsignedAttrs != null) { v.add(new DERTaggedObject(false, 1, unsignedAttrs)); } signerInfo = org.bouncycastle.asn1.cms.SignerInfo.getInstance(new DERSequence(v)); // Extend SignedData v = new ASN1EncodableVector(); v.add(content.getVersion()); v.add(content.getDigestAlgorithms()); v.add(content.getEncapContentInfo()); // Skipping certificates <- updated // Skipping CRLs <- updated v.add(new DERSet(signerInfo)); // <- updated content = org.bouncycastle.asn1.cms.SignedData.getInstance(new DERSequence(v)); // Extend ContentInfo v = new ASN1EncodableVector(); v.add(contentInfo.getContentType()); v.add(new DERTaggedObject(true, 0, content)); // <- updated contentInfo = org.bouncycastle.asn1.cms.ContentInfo.getInstance(new DERSequence(v)); return contentInfo; }
From source file:de.tsenger.animamea.Operator.java
License:Open Source License
private static SecurityInfos decodeEFCardSecurity(byte[] data) throws IOException, CertificateException, NoSuchProviderException, CMSException, OperatorCreationException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); ASN1Sequence asnSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(data); ContentInfo contentInfo = ContentInfo.getInstance(asnSeq); DERSequence derSeq = (DERSequence) contentInfo.getContent(); System.out.println("ContentType: " + contentInfo.getContentType().toString()); SignedData cardSecurity = SignedData.getInstance(derSeq); //Get SecurityInfos ContentInfo encapContentInfo = cardSecurity.getEncapContentInfo(); DEROctetString octString = (DEROctetString) encapContentInfo.getContent(); SecurityInfos si = new SecurityInfos(); si.decode(octString.getOctets());//from w w w . j a v a 2s . co m return si; }
From source file:de.tsenger.sandbox.CardSecurityParser.java
License:Open Source License
/** * @param args/*from w w w. ja v a2 s .co m*/ * @throws Exception */ public static void main(String[] args) throws Exception { byte[] efcsBytes = readBinaryFile("/home/tsenger/Desktop/EFCardSecurity.bin"); ASN1Sequence asnSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(efcsBytes); ContentInfo contentInfo = ContentInfo.getInstance(asnSeq); System.out.println(contentInfo.getContentType()); DERSequence derSeq = (DERSequence) contentInfo.getContent(); System.out.println(HexString.bufferToHex(derSeq.getEncoded(null))); SignedData signedData = SignedData.getInstance(derSeq); System.out.println("CMSVersion: " + signedData.getVersion().getValue().intValue()); ContentInfo contentInfo2 = signedData.getEncapContentInfo(); System.out.println(contentInfo2.getContentType()); DEROctetString octString = (DEROctetString) contentInfo2.getContent(); System.out.println("OctetString:\n" + HexString.bufferToHex(octString.getEncoded(null))); System.out.println("OctetString:\n" + HexString.bufferToHex(octString.getOctets())); SecurityInfos si = new SecurityInfos(); si.decode(octString.getOctets()); System.out.println(si); byte[] parameter = si.getChipAuthenticationPublicKeyInfoList().get(0).getPublicKey().getPublicKey(); System.out.println(HexString.bufferToHex(parameter)); System.out.println("Key Referenz: " + si.getChipAuthenticationPublicKeyInfoList().get(0).getKeyId()); System.out.println("CA OID: " + si.getChipAuthenticationPublicKeyInfoList().get(0).getPublicKey().getAlgorithm().getAlgorithm()); }
From source file:es.gob.afirma.applet.CMSInformation.java
License:Open Source License
/** * Obtiene la información de diferentes tipos de formatos. * @param doj Etiqueta ASN.1 de la que se obtienen los datos. * @param envelopeType Tipo de formato: * <li>0: EnvelopedData</li> * <li>1: AuthenticatedData</li> * <li>2: AuthEnvelopedData</li> * <li>3: SignedAndEnvelopedData</li> * <li>4: SignedData</li>/*ww w .j a v a 2s . c o m*/ * <li>5: Encrypted</li> * @param tipoDetalle Tipo de datos (literal) * @param signBinaryType Tipo de firmado binario (CADES o CMS) * @return Representación de los datos. */ private static String extractData(final ASN1TaggedObject doj, final int envelopeType, final String tipoDetalle, final int signBinaryType) { String detalle = ""; //$NON-NLS-1$ detalle = detalle + tipoDetalle + CR; ASN1Set rins = null; EncryptedContentInfo encryptedContentInfo = null; ASN1Set unprotectedAttrs = null; ASN1Integer version = null; AlgorithmIdentifier aid = null; ContentInfo ci = null; ASN1Set authAttrs = null; ASN1Set ds = null; ASN1Set signerInfosSd = null; switch (envelopeType) { case TYPE_ENVELOPED_DATA: final EnvelopedData enveloped = EnvelopedData.getInstance(doj.getObject()); version = enveloped.getVersion(); rins = enveloped.getRecipientInfos(); encryptedContentInfo = enveloped.getEncryptedContentInfo(); unprotectedAttrs = enveloped.getUnprotectedAttrs(); break; case TYPE_AUTHENTICATED_DATA: final AuthenticatedData authenticated = AuthenticatedData.getInstance(doj.getObject()); version = authenticated.getVersion(); rins = authenticated.getRecipientInfos(); aid = authenticated.getMacAlgorithm(); ci = authenticated.getEncapsulatedContentInfo(); authAttrs = authenticated.getAuthAttrs(); unprotectedAttrs = authenticated.getUnauthAttrs(); break; case TYPE_AUTHENTICATED_ENVELOPED_DATA: final AuthEnvelopedData authEnveloped = AuthEnvelopedData.getInstance(doj.getObject()); version = authEnveloped.getVersion(); rins = authEnveloped.getRecipientInfos(); encryptedContentInfo = authEnveloped.getAuthEncryptedContentInfo(); authAttrs = authEnveloped.getAuthAttrs(); unprotectedAttrs = authEnveloped.getUnauthAttrs(); break; case TYPE_SIGNED_ENVELOPED_DATA: final SignedAndEnvelopedData signedEnv = new SignedAndEnvelopedData((ASN1Sequence) doj.getObject()); version = signedEnv.getVersion(); rins = signedEnv.getRecipientInfos(); encryptedContentInfo = signedEnv.getEncryptedContentInfo(); signerInfosSd = signedEnv.getSignerInfos(); break; case TYPE_SIGNED_DATA: final SignedData signed = SignedData.getInstance(doj.getObject()); version = signed.getVersion(); ds = signed.getDigestAlgorithms(); ci = signed.getEncapContentInfo(); signerInfosSd = signed.getSignerInfos(); break; case TYPE_ENCRYPTED_DATA: final ASN1Sequence encrypted = (ASN1Sequence) doj.getObject(); version = ASN1Integer.getInstance(encrypted.getObjectAt(0)); encryptedContentInfo = EncryptedContentInfo.getInstance(encrypted.getObjectAt(1)); if (encrypted.size() == 3) { unprotectedAttrs = (ASN1Set) encrypted.getObjectAt(2); } break; default: throw new IllegalArgumentException("Tipo de sobre no soportado: " + envelopeType); //$NON-NLS-1$ } //obtenemos la version detalle = detalle + AppletMessages.getString("CMSInformation.1") + SP + version + CR; //$NON-NLS-1$ //recipientInfo if (rins != null) { if (envelopeType != TYPE_SIGNED_DATA && envelopeType != TYPE_ENCRYPTED_DATA && rins.size() > 0) { detalle = detalle + AppletMessages.getString("CMSInformation.13") + CR; //$NON-NLS-1$ } for (int i = 0; i < rins.size(); i++) { final KeyTransRecipientInfo kti = KeyTransRecipientInfo .getInstance(RecipientInfo.getInstance(rins.getObjectAt(i)).getInfo()); detalle = detalle + AppletMessages.getString("CMSInformation.14") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$ final AlgorithmIdentifier diAlg = kti.getKeyEncryptionAlgorithm(); //issuer y serial final IssuerAndSerialNumber iss = (IssuerAndSerialNumber) SignerIdentifier .getInstance(kti.getRecipientIdentifier().getId()).getId(); detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$ + iss.getName().toString() + CR; detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$ + CR; // el algoritmo de cifrado de los datos AOCipherAlgorithm algorithm = null; final AOCipherAlgorithm[] algos = AOCipherAlgorithm.values(); // obtenemos el algoritmo usado para cifrar la pass for (final AOCipherAlgorithm algo : algos) { if (algo.getOid().equals(diAlg.getAlgorithm().toString())) { algorithm = algo; } } if (algorithm != null) { detalle = detalle + TB + AppletMessages.getString("CMSInformation.17") + SP //$NON-NLS-1$ + algorithm.getName() + CR; } else { detalle = detalle + TB + AppletMessages.getString("CMSInformation.18") + SP //$NON-NLS-1$ + diAlg.getAlgorithm() + CR; } } } if (envelopeType == TYPE_ENVELOPED_DATA || envelopeType == TYPE_ENCRYPTED_DATA) { //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); } else if (envelopeType == TYPE_AUTHENTICATED_DATA && aid != null && ci != null) { // mac algorithm detalle = detalle + AppletMessages.getString("CMSInformation.20") + SP + aid.getAlgorithm() + CR; //$NON-NLS-1$ //digestAlgorithm final ASN1Sequence seq = (ASN1Sequence) doj.getObject(); final ASN1TaggedObject da = (ASN1TaggedObject) seq.getObjectAt(4); final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObject()); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$ detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs); } else if (envelopeType == TYPE_AUTHENTICATED_ENVELOPED_DATA) { detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); detalle = getObligatorieAtrib(signBinaryType, detalle, authAttrs); } else if (envelopeType == TYPE_SIGNED_ENVELOPED_DATA) { //algoritmo de firma final ASN1Sequence seq = (ASN1Sequence) doj.getObject(); final ASN1Set da = (ASN1Set) seq.getObjectAt(2); final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(da.getObjectAt(0)); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ //obtenemos datos de los datos cifrados. detalle = detalle + AppletMessages.getString("CMSInformation.19") + CR; //$NON-NLS-1$ detalle = detalle + getEncryptedContentInfo(encryptedContentInfo); } else if (envelopeType == TYPE_SIGNED_DATA && ci != null && ds != null) { //algoritmo de firma final AlgorithmIdentifier dai = AlgorithmIdentifier.getInstance(ds.getObjectAt(0)); detalle = detalle + AppletMessages.getString("CMSInformation.21") + SP + dai.getAlgorithm() + CR; //$NON-NLS-1$ detalle = detalle + AppletMessages.getString("CMSInformation.22") + SP + ci.getContentType() + CR; //$NON-NLS-1$ } //obtenemos lo atributos opcionales if (envelopeType != TYPE_SIGNED_ENVELOPED_DATA) { if (unprotectedAttrs == null) { detalle = detalle + AppletMessages.getString("CMSInformation.28") + CR; //$NON-NLS-1$ } else { final String atributos = getUnSignedAttributes(unprotectedAttrs.getObjects()); detalle = detalle + AppletMessages.getString("CMSInformation.29") + CR; //$NON-NLS-1$ detalle = detalle + atributos; } } else if ((envelopeType == TYPE_SIGNED_ENVELOPED_DATA || envelopeType == TYPE_SIGNED_DATA) && signerInfosSd != null) { //obtenemos el(los) firmate(s) if (signerInfosSd.size() > 0) { detalle = detalle + AppletMessages.getString("CMSInformation.30") + CR; //$NON-NLS-1$ } for (int i = 0; i < signerInfosSd.size(); i++) { final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i)); detalle = detalle + AppletMessages.getString("CMSInformation.31") + SP + (i + 1) + ":" + CR; //$NON-NLS-1$//$NON-NLS-2$ // version detalle = detalle + TB + AppletMessages.getString("CMSInformation.1") + SP + si.getVersion() + CR; //$NON-NLS-1$ //signerIdentifier final SignerIdentifier sident = si.getSID(); final IssuerAndSerialNumber iss = IssuerAndSerialNumber.getInstance(sident.getId()); detalle = detalle + TB + AppletMessages.getString("CMSInformation.15") + SP //$NON-NLS-1$ + iss.getName().toString() + CR; detalle = detalle + TB + AppletMessages.getString("CMSInformation.16") + SP + iss.getSerialNumber() //$NON-NLS-1$ + CR; //digestAlgorithm final AlgorithmIdentifier algId = si.getDigestAlgorithm(); detalle = detalle + TB + AppletMessages.getString("CMSInformation.35") + SP + algId.getAlgorithm() //$NON-NLS-1$ + CR; //obtenemos lo atributos obligatorios final ASN1Set sa = si.getAuthenticatedAttributes(); String satributes = ""; //$NON-NLS-1$ if (sa != null) { satributes = getsignedAttributes(sa, signBinaryType); } detalle = detalle + TB + AppletMessages.getString("CMSInformation.36") + CR; //$NON-NLS-1$ detalle = detalle + satributes; } } return detalle; }
From source file:es.gob.afirma.signers.cms.CoSigner.java
License:Open Source License
/** Constructor de la clase. Se crea una cofirma a partir de los datos del * firmante y el archivo que se firma.// w w w . j a va 2 s . c o m * @param signatureAlgorithm Algoritmo para la firma * @param signerCertificateChain Cadena de certificados para la construccion de los parametros * de firma. * @param sign Archivo que contiene las firmas. * @param dataType Identifica el tipo del contenido a firmar. * @param key Clave privada del firmante. * @param atrib Atributos firmados adicionales. * @param uatrib Atributos no firmados adicionales. * @param digest Hash a aplicar en la firma. * @return El archivo de firmas con la nueva firma. * @throws java.io.IOException Si ocurre algún problema leyendo o escribiendo los datos * @throws java.security.NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de * firma o huella digital * @throws java.security.cert.CertificateException Si se produce alguna excepción con * los certificados de firma. * @throws ContainsNoDataException Cuando la firma no contiene los datos * ni fue generada con el mismo algoritmo de firma. */ byte[] coSigner(final String signatureAlgorithm, final X509Certificate[] signerCertificateChain, final byte[] sign, final String dataType, final PrivateKey key, final Map<String, byte[]> atrib, final Map<String, byte[]> uatrib, final byte[] digest) throws IOException, NoSuchAlgorithmException, CertificateException, ContainsNoDataException { byte[] messageDigest = digest != null ? digest.clone() : null; // LEEMOS EL FICHERO QUE NOS INTRODUCEN final ASN1InputStream is = new ASN1InputStream(sign); final ASN1Sequence dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID SignedData e.nextElement(); // Contenido de SignedData final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject(); // Contenido del SignedData final SignedData sd = SignedData.getInstance(contentSignedData); // 3. CONTENTINFO // si se introduce el contenido o no final ContentInfo encInfo = sd.getEncapContentInfo(); final DEROctetString contenido = (DEROctetString) encInfo.getContent(); byte[] contenidoDatos = null; if (contenido != null) { contenidoDatos = AOUtil.getDataFromInputStream(contenido.getOctetStream()); } // 4. CERTIFICADOS // obtenemos la lista de certificados ASN1Set certificates = null; final ASN1Set certificatesSigned = sd.getCertificates(); final ASN1EncodableVector vCertsSig = new ASN1EncodableVector(); final Enumeration<?> certs = certificatesSigned.getObjects(); // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO while (certs.hasMoreElements()) { vCertsSig.add((ASN1Encodable) certs.nextElement()); } if (signerCertificateChain.length != 0) { final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>(); for (final X509Certificate element : signerCertificateChain) { ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded()))); } certificates = SigUtils.fillRestCerts(ce, vCertsSig); } // buscamos que tipo de algoritmo es y lo codificamos con su OID final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm); final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm)); // Identificador del firmante ISSUER AND SERIAL-NUMBER final TBSCertificateStructure tbs = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate())); final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()), tbs.getSerialNumber().getValue()); final SignerIdentifier identifier = new SignerIdentifier(encSid); // // ATRIBUTOS // atributos firmados ASN1Set signedAttr = null; // atributos no firmados. final ASN1Set unSignedAttr = generateUnsignerInfo(uatrib); // // FIN ATRIBUTOS // digEncryptionAlgorithm final AlgorithmIdentifier encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$ // 5. SIGNERINFO // raiz de la secuencia de SignerInfo // Obtenemos los signerInfos del SignedData final ASN1Set signerInfosSd = sd.getSignerInfos(); // introducimos los SignerInfos Existentes final ASN1EncodableVector signerInfos = new ASN1EncodableVector(); // introducimos el nuevo SignerInfo del firmante actual. // Secuencia: // 1.- Si cofirmamos sin datos en el mismo algoritmo de hash que la // firma // original sacamos el messagedigest de la firma previa. // 2.- Si no es el mismo algoritmo, miramos si nos ha llegado un // messagedigest // como parametro del metodo, que quiere decir que se ha calculado // externamente // (en el fondo sera que no se ha sobreescrito el parametro, con lo que // si llego // != null, seguira siendo != null) // 3.- Si no es ninguno de los dos casos, no podemos firmar for (int i = 0; i < signerInfosSd.size(); i++) { final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i)); final AlgorithmIdentifier algHash = si.getDigestAlgorithm(); // Solo si coninciden los algos puedo sacar el hash de dentro if (algHash.getAlgorithm().toString().equals(AOAlgorithmID.getOID(digestAlgorithm))) { final ASN1Set signedAttrib = si.getAuthenticatedAttributes(); for (int s = 0; s < signedAttrib.size(); s++) { final ASN1Sequence elemento = (ASN1Sequence) signedAttrib.getObjectAt(s); final ASN1ObjectIdentifier oids = (ASN1ObjectIdentifier) elemento.getObjectAt(0); if (CMSAttributes.messageDigest.getId().toString().equals(oids.toString())) { final DERSet derSetHash = (DERSet) elemento.getObjectAt(1); final DEROctetString derHash = (DEROctetString) derSetHash.getObjectAt(0); messageDigest = derHash.getOctets(); } } } signerInfos.add(si); } // atributos firmados if (contenidoDatos != null) { signedAttr = generateSignerInfo(digestAlgorithm, contenidoDatos, dataType, atrib); } else if (messageDigest != null) { signedAttr = generateSignerInfoFromHash(signerCertificateChain[0], messageDigest, dataType, atrib); } else { // En este caso no puedo usar un hash de fuera, ya que no me han // pasado datos ni // huellas digitales, solo un fichero de firma throw new ContainsNoDataException( "No se puede crear la cofirma ya que no se han encontrado ni los datos firmados ni una huella digital compatible con el algoritmo de firma"); //$NON-NLS-1$ } final ASN1OctetString sign2; try { sign2 = firma(signatureAlgorithm, key); } catch (final Exception ex) { throw new IOException("Error al generar la firma: " + ex, ex); //$NON-NLS-1$ } // Creamos los signerInfos del SignedData signerInfos.add(new SignerInfo(identifier, digAlgId, signedAttr, encAlgId, sign2, unSignedAttr// null //unsignedAttr )); // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedData, new SignedData(sd.getDigestAlgorithms(), encInfo, certificates, null, new DERSet(signerInfos)// unsignedAttr )).getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.signers.cms.CounterSigner.java
License:Open Source License
/** Constructor de la clase. Se crea una contrafirma a partir de los datos * del firmante, el archivo que se firma y del archivo que contiene las * firmas.<br>// w w w .j ava 2 s . c o m * @param parameters Parámetros necesarios que contienen tanto la firma del * archivo a firmar como los datos del firmante. * @param data Archivo que contiene las firmas. * @param targetType Lo que se quiere firmar. Puede ser el árbol completo, * las hojas, un nodo determinado o unos determinados firmantes. * @param targets Nodos objetivos a firmar. * @param key Clave privada a usar para firmar. * @param certChain Cadena de certificados del firmante. * @param dataType Identifica el tipo del contenido a firmar. * @param atri Atributo firmado que agregar a la firma. * @param uatri Atributo no firmado que agregar a la firma. * @return El archivo de firmas con la nueva firma. * @throws java.io.IOException Si ocurre algún problema leyendo o escribiendo los * datos * @throws java.security.NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de firma o huella * digital. * @throws java.security.cert.CertificateException Si se produce alguna excepción con los certificados de * firma. * @throws AOException Cuando ocurre cualquier error no contemplado por el resto de * las excepciones declaradas */ byte[] counterSigner(final P7ContentSignerParameters parameters, final byte[] data, final CounterSignTarget targetType, final int[] targets, final PrivateKey key, final java.security.cert.Certificate[] certChain, final String dataType, final Map<String, byte[]> atri, final Map<String, byte[]> uatri) throws IOException, NoSuchAlgorithmException, CertificateException, AOException { this.atrib2 = atri; this.uatrib2 = uatri; // LEEMOS EL FICHERO QUE NOS INTRODUCEN 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 SignedData e.nextElement(); // Contenido de SignedData final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject(); final SignedData sd = SignedData.getInstance(contentSignedData); // Obtenemos los signerInfos del SignedData final ASN1Set signerInfosSd = sd.getSignerInfos(); // 4. CERTIFICADOS // obtenemos la lista de certificados ASN1Set certificates = null; final ASN1Set certificatesSigned = sd.getCertificates(); final ASN1EncodableVector vCertsSig = new ASN1EncodableVector(); final Enumeration<?> certs = certificatesSigned.getObjects(); // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO while (certs.hasMoreElements()) { vCertsSig.add((ASN1Encodable) certs.nextElement()); } if (certChain.length != 0) { vCertsSig.add(Certificate.getInstance(ASN1Primitive.fromByteArray(certChain[0].getEncoded()))); certificates = new BERSet(vCertsSig); } // CRLS no usado final ASN1Set certrevlist = null; // 5. SIGNERINFO // raiz de la secuencia de SignerInfo ASN1EncodableVector signerInfos = new ASN1EncodableVector(); // FIRMA EN ARBOL if (targetType.equals(CounterSignTarget.TREE)) { signerInfos = counterTree(signerInfosSd, parameters, key, certChain); } // FIRMA DE LAS HOJAS else if (targetType.equals(CounterSignTarget.LEAFS)) { signerInfos = counterLeaf(signerInfosSd, parameters, key, certChain); } // FIRMA DE NODOS else if (targetType.equals(CounterSignTarget.NODES)) { // Firma de Nodos SignedData sigDat; SignedData aux = sd; int nodo = 0; for (int i = targets.length - 1; i >= 0; i--) { nodo = targets[i]; signerInfos = counterNode(aux, parameters, key, certChain, nodo); sigDat = new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates, certrevlist, new DERSet(signerInfos)); // Esto se realiza así por problemas con los casting. final ASN1InputStream sd2 = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER)); final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del SignedData sd2.close(); aux = SignedData.getInstance(contentSignedData2); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedData, aux).getEncoded(ASN1Encoding.DER); } else if (targetType.equals(CounterSignTarget.SIGNERS)) { // Firma de Nodos SignedData sigDat; SignedData aux = sd; int nodo = 0; for (int i = targets.length - 1; i >= 0; i--) { nodo = targets[i]; signerInfos = counterNode(aux, parameters, key, certChain, nodo); sigDat = new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates, certrevlist, new DERSet(signerInfos)); // Esto se realiza así por problemas con los casting. final ASN1InputStream sd2 = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER)); final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del SignedData sd2.close(); aux = SignedData.getInstance(contentSignedData2); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedData, aux).getEncoded(ASN1Encoding.DER); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedData, new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates, certrevlist, new DERSet(signerInfos))) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.signers.multi.cades.CAdESCoSigner.java
License:Open Source License
/** Constructor de la clase. Se crea una cofirma a partir de los datos del * firmante y del archivo que contiene las firmas. * @param signatureAlgorithm Algoritmo para la firma * @param signerCertificateChain Cadena de certificados para la construccion de los parametros de firma. * @param signature Archivo que contiene las firmas. * @param policy Política de firma * @param signingCertificateV2// w w w. j a v a2s. c om * <code>true</code> si se desea usar la versión 2 del * atributo <i>Signing Certificate</i> <code>false</code> para * usar la versión 1 * @param key Clave privada usada para firmar. * @param certChain Cadena de certificados del firmante. * @param md Huella digital específica para una firma. * @param contentType Tipo de contenido definido por su OID. * @param contentDescription Descripció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 El archivo de firmas con la nueva firma. * @throws java.io.IOException Si ocurre algún problema leyendo o escribiendo los datos * @throws NoSuchAlgorithmException Si no se soporta alguno de los algoritmos de firma o huella digital * @throws CertificateException Si se produce alguna excepción con los certificados de firma. * @throws ContainsNoDataException Cuando la firma no contiene los datos ni fue generada con el mismo * algoritmo de firma. */ byte[] coSigner(final String signatureAlgorithm, final X509Certificate[] signerCertificateChain, final InputStream signature, final AdESPolicy policy, final boolean signingCertificateV2, final PrivateKey key, final java.security.cert.Certificate[] certChain, final byte[] md, final String contentType, final String contentDescription, final List<CommitmentTypeIndicationBean> ctis, final CAdESSignerMetadata csm) throws IOException, NoSuchAlgorithmException, CertificateException, ContainsNoDataException { // LEEMOS EL FICHERO QUE NOS INTRODUCEN final ASN1InputStream is = new ASN1InputStream(signature); final ASN1Sequence dsq = (ASN1Sequence) is.readObject(); is.close(); final Enumeration<?> e = dsq.getObjects(); // Elementos que contienen los elementos OID SignedData e.nextElement(); // Contenido de SignedData final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject();// contenido // del // SignedData final SignedData sd = SignedData.getInstance(contentSignedData); // 3. CONTENTINFO // si se introduce el contenido o no final ContentInfo encInfo = sd.getEncapContentInfo(); final DEROctetString contenido = (DEROctetString) encInfo.getContent(); byte[] contenidoDatos = null; if (contenido != null) { contenidoDatos = AOUtil.getDataFromInputStream(contenido.getOctetStream()); } // 4. CERTIFICADOS // obtenemos la lista de certificados ASN1Set certificates = null; final ASN1Set certificatesSigned = sd.getCertificates(); final ASN1EncodableVector vCertsSig = new ASN1EncodableVector(); final Enumeration<?> certs = certificatesSigned.getObjects(); // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO while (certs.hasMoreElements()) { vCertsSig.add((ASN1Encodable) certs.nextElement()); } if (signerCertificateChain.length != 0) { final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>(); for (final X509Certificate element : signerCertificateChain) { ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded()))); } certificates = SigUtils.fillRestCerts(ce, vCertsSig); } // buscamos que timo de algoritmo es y lo codificamos con su OID final String digestAlgorithm = AOSignConstants.getDigestAlgorithmName(signatureAlgorithm); final AlgorithmIdentifier digAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID(digestAlgorithm)); // Identificador del firmante ISSUER AND SERIAL-NUMBER final TBSCertificateStructure tbs = TBSCertificateStructure .getInstance(ASN1Primitive.fromByteArray(signerCertificateChain[0].getTBSCertificate())); final IssuerAndSerialNumber encSid = new IssuerAndSerialNumber(X500Name.getInstance(tbs.getIssuer()), tbs.getSerialNumber().getValue()); final SignerIdentifier identifier = new SignerIdentifier(encSid); // digEncryptionAlgorithm final AlgorithmIdentifier encAlgId = SigUtils.makeAlgId(AOAlgorithmID.getOID("RSA")); //$NON-NLS-1$ // 5. SIGNERINFO // raiz de la secuencia de SignerInfo // Obtenemos los signerInfos del SignedData final ASN1Set signerInfosSd = sd.getSignerInfos(); // introducimos los SignerInfos Existentes final ASN1EncodableVector signerInfos = new ASN1EncodableVector(); // introducimos el nuevo SignerInfo del firmante actual. byte[] messageDigest = md != null ? md.clone() : null; for (int i = 0; i < signerInfosSd.size(); i++) { final SignerInfo si = SignerInfo.getInstance(signerInfosSd.getObjectAt(i)); final AlgorithmIdentifier algHash = si.getDigestAlgorithm(); if (algHash.getAlgorithm().toString().equals(AOAlgorithmID.getOID(digestAlgorithm))) { final ASN1Set signedAttrib = si.getAuthenticatedAttributes(); for (int s = 0; s < signedAttrib.size(); s++) { final ASN1Sequence elemento = (ASN1Sequence) signedAttrib.getObjectAt(s); final ASN1ObjectIdentifier oids = (ASN1ObjectIdentifier) elemento.getObjectAt(0); if (CMSAttributes.messageDigest.getId().equals(oids.toString())) { final DERSet derSetHash = (DERSet) elemento.getObjectAt(1); final DEROctetString derHash = (DEROctetString) derSetHash.getObjectAt(0); messageDigest = derHash.getOctets(); } } } signerInfos.add(si); } // // ATRIBUTOS ASN1Set signedAttr; // atributos firmados if (contenidoDatos != null) { final ASN1EncodableVector contextExpecific = CAdESUtils.generateSignerInfo(signerCertificateChain[0], digestAlgorithm, contenidoDatos, policy, signingCertificateV2, null, // MessageDigest new Date(), false, contentType, contentDescription, ctis, csm); this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific)); signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific)); } else if (messageDigest != null) { final ASN1EncodableVector contextExpecific = CAdESUtils.generateSignerInfo(signerCertificateChain[0], digestAlgorithm, null, policy, signingCertificateV2, messageDigest, new Date(), false, contentType, contentDescription, ctis, csm); this.signedAttr2 = SigUtils.getAttributeSet(new AttributeTable(contextExpecific)); signedAttr = SigUtils.getAttributeSet(new AttributeTable(contextExpecific)); } else { throw new ContainsNoDataException( "No se puede crear la cofirma ya que no se han encontrado ni los datos firmados ni una huella digital compatible con el algoritmo de firma"); //$NON-NLS-1$ } final ASN1OctetString sign2; try { sign2 = firma(signatureAlgorithm, key, certChain); } catch (final AOException ex) { throw new IOException("Error al realizar la firma: " + ex, ex); //$NON-NLS-1$ } // Creamos los signerInfos del SignedData signerInfos.add(new SignerInfo(identifier, digAlgId, signedAttr, encAlgId, sign2, null // unsignedAttr )); // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedData, new SignedData(sd.getDigestAlgorithms(), encInfo, certificates, null, // CRLS no usado new DERSet(signerInfos)// unsignedAttr )).getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.signers.multi.cades.CAdESCounterSigner.java
License:Open Source License
/** Crea una contrafirma a partir de los datos * del firmante, el archivo que se firma y del archivo que contiene las * firmas.<br>/*from w w w . j a v a 2 s.com*/ * @param parameters * parámetros necesarios que contienen tanto la firma del * archivo a firmar como los datos del firmante. * @param data * Archivo que contiene las firmas. * @param targetType * Lo que se quiere firmar. Puede ser el árbol completo, * las hojas, un nodo determinado o unos determinados firmantes. * @param targets * Nodos objetivos a firmar. * @param key Clave privada a usar para firmar. * @param certChain Cadena de certificados del firmante. * @param policy Política de firma * @param signingCertificateV2 * <code>true</code> si se desea usar la versión 2 del * atributo <i>Signing Certificate</i> <code>false</code> para * usar la versión 1 * @param contentDescription Descripció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 El archivo de firmas con la nueva firma. * @throws IOException Cuando se produce algun error con la lectura o escritura de datos. * @throws NoSuchAlgorithmException Excepción cuando no se encuentra el algoritmo de * firma. * @throws CertificateException Si se produce alguna excepción con los certificados de * firma. * @throws AOException Cuando ocurre alguno error con contemplado por las otras * excepciones declaradas */ byte[] counterSigner(final P7ContentSignerParameters parameters, final byte[] data, final CounterSignTarget targetType, final int[] targets, final PrivateKey key, final java.security.cert.Certificate[] certChain, final AdESPolicy policy, final boolean signingCertificateV2, final String contentDescription, final List<CommitmentTypeIndicationBean> ctis, final CAdESSignerMetadata csm) throws IOException, NoSuchAlgorithmException, CertificateException, AOException { // LEEMOS EL FICHERO QUE NOS INTRODUCEN 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 SignedData e.nextElement(); // Contenido de SignedData final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject(); final SignedData sd = SignedData.getInstance(contentSignedData); // Obtenemos los signerInfos del SignedData final ASN1Set signerInfosSd = sd.getSignerInfos(); // 4. CERTIFICADOS // obtenemos la lista de certificados ASN1Set certificates = null; final ASN1Set certificatesSigned = sd.getCertificates(); final ASN1EncodableVector vCertsSig = new ASN1EncodableVector(); final Enumeration<?> certs = certificatesSigned.getObjects(); // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO while (certs.hasMoreElements()) { vCertsSig.add((ASN1Encodable) certs.nextElement()); } // e introducimos los del firmante actual. if (certChain.length != 0) { final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>(); for (final java.security.cert.Certificate element : certChain) { ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded()))); } certificates = SigUtils.fillRestCerts(ce, vCertsSig); } // CRLS no usado final ASN1Set certrevlist = null; // 5. SIGNERINFO // raiz de la secuencia de SignerInfo ASN1EncodableVector signerInfos = new ASN1EncodableVector(); // FIRMA EN ARBOL if (targetType.equals(CounterSignTarget.TREE)) { signerInfos = counterTree(signerInfosSd, parameters, key, certChain, contentDescription, policy, signingCertificateV2, ctis, csm); } // FIRMA DE LAS HOJAS else if (targetType.equals(CounterSignTarget.LEAFS)) { signerInfos = counterLeaf(signerInfosSd, parameters, key, certChain, contentDescription, policy, signingCertificateV2, ctis, csm); } // FIRMA DE NODOS else if (targetType.equals(CounterSignTarget.NODES)) { // Firma de Nodos SignedData sigDat; SignedData aux = sd; int nodo = 0; for (int i = targets.length - 1; i >= 0; i--) { nodo = targets[i]; signerInfos = counterNode(aux, parameters, key, certChain, contentDescription, nodo, policy, signingCertificateV2, ctis, csm); sigDat = new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates, certrevlist, new DERSet(signerInfos)); // Esto se realiza asi por problemas con los casting. final ASN1InputStream sd2 = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER)); final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del SignedData sd2.close(); aux = SignedData.getInstance(contentSignedData2); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedData, aux).getEncoded(ASN1Encoding.DER); } // FIRMA DE LOS SIGNERS else if (targetType.equals(CounterSignTarget.SIGNERS)) { // Firma de Nodos SignedData sigDat; SignedData aux = sd; int nodo = 0; for (int i = targets.length - 1; i >= 0; i--) { nodo = targets[i]; signerInfos = counterNode(aux, parameters, key, certChain, contentDescription, nodo, policy, signingCertificateV2, ctis, csm); sigDat = new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates, certrevlist, new DERSet(signerInfos)); // Esto se realiza así por problemas con los casting. final ASN1InputStream sd2 = new ASN1InputStream(sigDat.getEncoded(ASN1Encoding.DER)); final ASN1Sequence contentSignedData2 = (ASN1Sequence) sd2.readObject();// contenido del SignedData sd2.close(); aux = SignedData.getInstance(contentSignedData2); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedData, aux).getEncoded(ASN1Encoding.DER); } // construimos el Signed Data y lo devolvemos return new ContentInfo(PKCSObjectIdentifiers.signedData, new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates, certrevlist, new DERSet(signerInfos))) .getEncoded(ASN1Encoding.DER); }
From source file:es.gob.afirma.signers.multi.cades.CAdESTriPhaseCounterSigner.java
License:Open Source License
/** Crea una contrafirma a partir de los datos * del firmante, el archivo que se firma y del archivo que contiene las * firmas.<br>/*from ww w .j a v a 2s .c om*/ * @param parameters * parámetros necesarios que contienen tanto la firma del * archivo a firmar como los datos del firmante. * @param data * Archivo que contiene las firmas. * @param targetType * Lo que se quiere firmar. Puede ser el árbol completo, * las hojas, un nodo determinado o unos determinados firmantes. * @param key Clave privada a usar para firmar. * @param certChain Cadena de certificados del firmante * @param policy Política de firma * @param signingCertificateV2 * <code>true</code> si se desea usar la versión 2 del * atributo <i>Signing Certificate</i> <code>false</code> para * usar la versión 1 * @param contentType * Tipo de contenido definido por su OID. * @param contentDescription * Descripción textual del tipo de contenido firmado. * @return El archivo de firmas con la nueva firma. * @throws java.io.IOException * Excepción cuando se produce algun error con lectura * escritura de ficheros. * @throws java.security.NoSuchAlgorithmException * Excepción cuando no se encuentra el algoritmo de * firma. * @throws java.security.cert.CertificateException * Si se produce alguna excepción con los certificados de * firma. * @throws AOException * Cuando ocurre alguno error con contemplado por las otras * excepciones declaradas */ public CAdESPreCounterSignResult preCounterSign(final P7ContentSignerParameters parameters, final byte[] data, final CounterSignTarget targetType, final PrivateKey key, final java.security.cert.Certificate[] certChain, final AdESPolicy policy, final boolean signingCertificateV2, final String contentType, final String contentDescription) throws IOException, NoSuchAlgorithmException, CertificateException, AOException { // Inicializamos el contador global y la lista de SignedDatas this.counterIndex = 0; this.signedDatas = new ArrayList<byte[]>(); // LEEMOS EL FICHERO QUE NOS INTRODUCEN 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 SignedData e.nextElement(); // Contenido de SignedData final ASN1TaggedObject doj = (ASN1TaggedObject) e.nextElement(); final ASN1Sequence contentSignedData = (ASN1Sequence) doj.getObject(); final SignedData sd = SignedData.getInstance(contentSignedData); // Obtenemos los signerInfos del SignedData final ASN1Set signerInfosSd = sd.getSignerInfos(); // 4. CERTIFICADOS // obtenemos la lista de certificados ASN1Set certificates = null; final ASN1Set certificatesSigned = sd.getCertificates(); final ASN1EncodableVector vCertsSig = new ASN1EncodableVector(); final Enumeration<?> certs = certificatesSigned.getObjects(); // COGEMOS LOS CERTIFICADOS EXISTENTES EN EL FICHERO while (certs.hasMoreElements()) { vCertsSig.add((ASN1Encodable) certs.nextElement()); } // e introducimos los del firmante actual. if (certChain.length != 0) { final List<ASN1Encodable> ce = new ArrayList<ASN1Encodable>(); for (final java.security.cert.Certificate element : certChain) { ce.add(Certificate.getInstance(ASN1Primitive.fromByteArray(element.getEncoded()))); } certificates = SigUtils.fillRestCerts(ce, vCertsSig); } // CRLS no usado final ASN1Set certrevlist = null; // 5. SIGNERINFO // raiz de la secuencia de SignerInfo ASN1EncodableVector signerInfos = new ASN1EncodableVector(); // FIRMA EN ARBOL if (CounterSignTarget.TREE.equals(targetType)) { signerInfos = counterTree(signerInfosSd, parameters, key, certChain, contentType, contentDescription, policy, signingCertificateV2); } // FIRMA DE LAS HOJAS else if (CounterSignTarget.LEAFS.equals(targetType)) { signerInfos = counterLeaf(signerInfosSd, parameters, key, certChain, contentType, contentDescription, policy, signingCertificateV2); } else { throw new IllegalArgumentException("Modo de contrafirma no soportado: " + targetType); //$NON-NLS-1$ } // construimos el Signed Data y lo devolvemos dentro del resultado return new CAdESPreCounterSignResult( new ContentInfo(PKCSObjectIdentifiers.signedData, new SignedData(sd.getDigestAlgorithms(), sd.getEncapContentInfo(), certificates, certrevlist, new DERSet(signerInfos))).getEncoded(ASN1Encoding.DER), this.signedDatas); }