/// <summary> /// Realiza la contrafirma de una firma CAdES existente /// </summary> /// <param name="sigDocument"></param> /// <param name="signerInfoNode"></param> /// <param name="parameters"></param> /// <returns></returns> public SignatureDocument CounterSign(SignatureDocument sigDocument, SignerInfoNode signerInfoNode, SignatureParameters parameters) { if (sigDocument == null) { throw new Exception("Se necesita una firma previa para poder realizar la cofirma"); } if (signerInfoNode == null) { throw new Exception("Se necesita especificar el nodo de firma para aplicar la contrafirma"); } CheckParameters(parameters); byte[] signature = null; using (MemoryStream ms = new MemoryStream(signerInfoNode.SignerInformation.GetSignature())) { byte[] toBeSigned = ToBeSigned(new CmsProcessableInputStream(ms), parameters, null, true); signature = parameters.Signer.SignData(toBeSigned, parameters.DigestMethod); } CustomCMSSignedDataGenerator generator = CreateSignedGenerator(new PreComputedSigner(signature), parameters, null); var result = generator.GenerateCounterSigners(signerInfoNode.SignerInformation); SignerInformation updatedSI = SignerInformation.AddCounterSigners(signerInfoNode.SignerInformation, result); List <X509Certificate> certs = new List <X509Certificate>(); IX509Store originalCertStore = sigDocument.SignedData.GetCertificates("Collection"); signerInfoNode.SignerInformation = updatedSI; CollectionUtilities.AddRange(certs, GetCertificatesFromStore(originalCertStore)); X509CertificateParser parser = new X509CertificateParser(); var signerCertificate = parser.ReadCertificate(parameters.Certificate.GetRawCertData()); if (!CheckCertExists(signerCertificate, originalCertStore)) { certs.Add(signerCertificate); } IX509Store certStore = X509StoreFactory.Create("Certificate/Collection", new X509CollectionStoreParameters(certs)); CmsSignedData newSignedData = CmsSignedData.ReplaceCertificatesAndCrls(sigDocument.SignedData, certStore, sigDocument.SignedData.GetCrls("Collection"), null); return(new SignatureDocument(newSignedData)); }