private static PrimarySignature RemoveUnsignedAttribute(PrimarySignature signature, Func <AttributeTable, AttributeTable> remover) { var bytes = signature.GetBytes(); var signedData = new CmsSignedData(bytes); var signerInfos = signedData.GetSignerInfos(); var signerInfo = GetFirstSignerInfo(signerInfos); var updatedAttributes = remover(signerInfo.UnsignedAttributes); var updatedSignerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedAttributes); var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo); var updatedSignedData = CmsSignedData.ReplaceSigners(signedData, updatedSignerInfos); return(PrimarySignature.Load(updatedSignedData.GetEncoded())); }
private SignerInformation GetSignerInformation(SignerInfoNode signerInfoNode) { if (signerInfoNode.CounterSignatures.Count > 0) { var nodes = GetCounterSignatures(signerInfoNode); BcCms.AttributeTable attributes = signerInfoNode.SignerInformation.UnsignedAttributes.Remove(CmsAttributes.CounterSignature); SignerInformation newSignerInformation = SignerInformation.ReplaceUnsignedAttributes(signerInfoNode.SignerInformation, attributes); return(SignerInformation.AddCounterSigners(newSignerInformation, new SignerInformationStore(nodes.ToArray()))); } else { return(signerInfoNode.SignerInformation); } }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData cmsSignedData , SignerInformation si, SignatureParameters parameters, Document originalDocument ) { si = base.ExtendCMSSignature(cmsSignedData, si, parameters, originalDocument); CAdESSignature signature = new CAdESSignature(cmsSignedData, si); //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); Attribute archiveTimeStamp = GetTimeStampAttribute(CAdESProfileA.id_aa_ets_archiveTimestampV2 , GetSignatureTsa(), digestAlgorithm, signature.GetArchiveTimestampData(0, originalDocument )); //unsignedAttrHash.Put(CAdESProfileA.id_aa_ets_archiveTimestampV2, archiveTimeStamp); unsignedAttrHash.Add(CAdESProfileA.id_aa_ets_archiveTimestampV2, archiveTimeStamp); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new AttributeTable (unsignedAttrHash)); return(newsi); }
private static SignedCms ModifyUnsignedAttributes(SignedCms signedCms, Func <AttributeTable, AttributeTable> modify) { byte[] bytes = signedCms.Encode(); var bcSignedCms = new CmsSignedData(bytes); SignerInformationStore signerInfos = bcSignedCms.GetSignerInfos(); SignerInformation signerInfo = GetFirstSignerInfo(signerInfos); AttributeTable updatedAttributes = modify(signerInfo.UnsignedAttributes); SignerInformation updatedSignerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedAttributes); var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo); CmsSignedData updatedBcSignedCms = CmsSignedData.ReplaceSigners(bcSignedCms, updatedSignerInfos); var updatedSignedCms = new SignedCms(); updatedSignedCms.Decode(updatedBcSignedCms.GetEncoded()); return(updatedSignedCms); }
protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData) { si = base.ExtendCMSSignature(signedData, si, parameters, originalData); using (var toTimestamp = new MemoryStream()) { DerObjectIdentifier attributeId; switch (GetExtendedValidationType()) { case 1: { attributeId = PkcsObjectIdentifiers.IdAAEtsEscTimeStamp; toTimestamp.Write(si.GetSignature()); // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS §6.3.5, // NOTE 2) toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAASignatureTimeStampToken].AttrValues.GetDerEncoded()); break; } case 2: { attributeId = PkcsObjectIdentifiers.IdAAEtsCertCrlTimestamp; break; } default: { return(si); } } toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs].AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsCertificateRefs].AttrValues.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs].AttrType.GetDerEncoded()); toTimestamp.Write(si.UnsignedAttributes[PkcsObjectIdentifiers.IdAAEtsRevocationRefs].AttrValues.GetDerEncoded()); var unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, SignatureTsa, toTimestamp.ToArray()); unsignedAttrHash.Add(attributeId, extendedTimeStamp); return(SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash))); } }
private static PrimarySignature RemoveRepositoryCountersignatureTimestamp(PrimarySignature signature) { var bytes = signature.GetBytes(); var signedData = new CmsSignedData(bytes); var signerInfos = signedData.GetSignerInfos(); var signerInfo = GetFirstSignerInfo(signerInfos); var countersignerInfos = signerInfo.GetCounterSignatures(); var countersignerInfo = GetFirstSignerInfo(countersignerInfos); var updatedCountersignerAttributes = countersignerInfo.UnsignedAttributes.Remove(new DerObjectIdentifier(Oids.SignatureTimeStampTokenAttribute)); var updatedCountersignerInfo = SignerInformation.ReplaceUnsignedAttributes(countersignerInfo, updatedCountersignerAttributes); var updatedSignerAttributes = signerInfo.UnsignedAttributes.Remove(new DerObjectIdentifier(Oids.Countersignature)); updatedSignerAttributes = updatedSignerAttributes.Add(CmsAttributes.CounterSignature, updatedCountersignerInfo.ToSignerInfo()); var updatedSignerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, updatedSignerAttributes); var updatedSignerInfos = new SignerInformationStore(updatedSignerInfo); var updatedSignedData = CmsSignedData.ReplaceSigners(signedData, updatedSignerInfos); return(PrimarySignature.Load(updatedSignedData.GetEncoded())); }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData , SignerInformation si, SignatureParameters parameters, Document originalData) { si = base.ExtendCMSSignature(signedData, si, parameters, originalData); //IDictionary<DerObjectIdentifier, Asn1Encodable> unsignedAttrs = si.UnsignedAttributes.ToDictionary(); IDictionary unsignedAttrs = si.UnsignedAttributes.ToDictionary(); CAdESSignature signature = new CAdESSignature(signedData, si.SignerID); DateTime signingTime = signature.GetSigningTime().Value; if (signingTime == null) { signingTime = parameters.SigningDate; } if (signingTime == null) { signingTime = DateTime.Now; } unsignedAttrs = ExtendUnsignedAttributes(unsignedAttrs, signature.GetSigningCertificate (), signingTime, signature.GetCertificateSource()); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable (unsignedAttrs)); return(newsi); }
private IList <SignerInformation> GetCounterSignatures(SignerInfoNode node) { List <SignerInformation> list = new List <SignerInformation>(); foreach (var counterSignNode in node.CounterSignatures) { if (counterSignNode.CounterSignatures.Count > 0) { var nodes = GetCounterSignatures(counterSignNode); BcCms.AttributeTable attributes = counterSignNode.SignerInformation.UnsignedAttributes.Remove(CmsAttributes.CounterSignature); SignerInformation newSignerInformation = SignerInformation.ReplaceUnsignedAttributes(counterSignNode.SignerInformation, attributes); list.Add(SignerInformation.AddCounterSigners(newSignerInformation, new SignerInformationStore(nodes.ToArray()))); } else { list.Add(counterSignNode.SignerInformation); } } return(list); }
public void Upgrade(SignatureDocument signatureDocument, SignerInfoNode signerInfoNode, UpgradeParameters parameters) { BcCms.AttributeTable unsigned = signerInfoNode.SignerInformation.UnsignedAttributes; IDictionary unsignedAttrHash = null; if (unsigned == null) { unsignedAttrHash = new Dictionary <DerObjectIdentifier, BcCms.Attribute>(); } else { unsignedAttrHash = signerInfoNode.SignerInformation.UnsignedAttributes.ToDictionary(); } BcCms.Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken , parameters.TsaClient, parameters.DigestMethod, signerInfoNode.SignerInformation.GetSignature()); unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(signerInfoNode.SignerInformation, new BcCms.AttributeTable(unsignedAttrHash)); signerInfoNode.SignerInformation = newsi; }
protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData) { if (si is null) { throw new ArgumentNullException(nameof(si)); } if (parameters is null) { throw new ArgumentNullException(nameof(parameters)); } SignerInformation newSi = base.ExtendCMSSignature(signedData, si, parameters, originalData); IDictionary unsignedAttrs = newSi.UnsignedAttributes.ToDictionary(); CAdESSignature signature = new CAdESSignature(signedData, si.SignerID); unsignedAttrs = ExtendUnsignedAttributes( unsignedAttrs, signature.SigningCertificate, parameters, signature.SigningTime.Value, signature.CertificateSource); return(SignerInformation.ReplaceUnsignedAttributes(newSi, new BcCms.AttributeTable(unsignedAttrs))); }
protected void Complete(Level?level, Stream embedded, Stream signed, Stream content, X509Certificate2 providedSigner, out TimemarkKey timemarkKey) { #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Information, 0, "Completing the message with of {0} bytes to level {1}", signed.Length, level); #else logger.LogInformation("Completing the message with of {0} bytes to level {1}", signed.Length, level); #endif //Create the objects we need var gen = new CmsSignedDataStreamGenerator(); var parser = new CmsSignedDataParser(signed); timemarkKey = new TimemarkKey(); //preset the digests so we can add the signers afterwards gen.AddDigests(parser.DigestOids); //Copy the content to the output Stream contentOut = gen.Open(embedded, parser.SignedContentType.Id, true); if (content != null) { content.CopyTo(contentOut); } else { parser.GetSignedContent().ContentStream.CopyTo(contentOut); } //Extract the various data from outer layer SignerInformation signerInfo = ExtractSignerInfo(parser); IX509Store embeddedCerts = parser.GetCertificates("Collection"); //Extract the various data from signer info timemarkKey.SignatureValue = signerInfo.GetSignature(); timemarkKey.SigningTime = ExtractSigningTime(signerInfo); timemarkKey.Signer = ExtractSignerCert(embeddedCerts, signerInfo, providedSigner); if (timemarkKey.Signer != null) { timemarkKey.SignerId = DotNetUtilities.FromX509Certificate(timemarkKey.Signer).GetSubjectKeyIdentifier(); } else { timemarkKey.SignerId = signerInfo.SignerID.ExtractSignerId(); } //Extract the various data from unsiged attributes of signer info IDictionary unsignedAttributes = signerInfo.UnsignedAttributes != null?signerInfo.UnsignedAttributes.ToDictionary() : new Hashtable(); TimeStampToken tst = ExtractTimestamp(unsignedAttributes); RevocationValues revocationInfo = ExtractRevocationInfo(unsignedAttributes); //quick check for an expected error and extrapolate some info if (timemarkKey.SignerId == null) { #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Error, 0, "We could not find any signer information"); #else logger.LogError("We could not find any signer information"); #endif throw new InvalidMessageException("The message does not contain any valid signer info"); } if (timemarkKey.SigningTime == default && tst != null) { #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Information, 0, "Implicit signing time is replaced with time-stamp time {1}", tst.TimeStampInfo.GenTime); #else logger.LogInformation("Implicit signing time is replaced with time-stamp time {1}", tst.TimeStampInfo.GenTime); #endif timemarkKey.SigningTime = tst.TimeStampInfo.GenTime; } //Are we missing embedded certs and should we add them? if ((embeddedCerts == null || embeddedCerts.GetMatches(null).Count <= 1) && timemarkKey.Signer != null && level != null) { embeddedCerts = GetEmbeddedCerts(timemarkKey); } if (embeddedCerts != null) { gen.AddCertificates(embeddedCerts); //add the existing or new embedded certs to the output. } //Are we missing timestamp and should we add them (not that time-mark authorities do not require a timestamp provider) if (tst == null && (level & Level.T_Level) == Level.T_Level && timestampProvider != null) { tst = GetTimestamp(timemarkKey); AddTimestamp(unsignedAttributes, tst); } //should be make sure we have the proper revocation info (it is hard to tell if we have everything, just go for it) if ((level & Level.L_Level) == Level.L_Level) { if (embeddedCerts != null && embeddedCerts.GetMatches(null).Count > 0) { //extend the revocation info with info about the embedded certs revocationInfo = GetRevocationValues(timemarkKey, embeddedCerts, revocationInfo); } if (tst != null) { //extend the revocation info with info about the TST revocationInfo = GetRevocationValues(tst, revocationInfo); } //update the unsigned attributes AddRevocationValues(unsignedAttributes, revocationInfo); } //Update the unsigned attributes of the signer info signerInfo = SignerInformation.ReplaceUnsignedAttributes(signerInfo, new BC::Asn1.Cms.AttributeTable(unsignedAttributes)); //Copy the signer gen.AddSigners(new SignerInformationStore(new SignerInformation[] { signerInfo })); contentOut.Close(); }
public byte[] FirmaFileBouncy(string NomeFile, X509Certificate2 cert, bool GiaFirmato, bool UsaTSA, string TSAurl, string TSAuser, string TSApass, out string RisFirma) { try { SHA256Managed hashSha256 = new SHA256Managed(); byte[] certHash = hashSha256.ComputeHash(cert.RawData); EssCertIDv2 essCert1 = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash); SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert1 }); Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2)); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(CertHAttribute); Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v); CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp(); var rsa = (RSACryptoServiceProvider)cert.PrivateKey; Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert); cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null); ArrayList certList = new ArrayList(); certList.Add(certCopy); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); cms.AddCertificates(st1); //mi ricavo il file da firmare FileInfo FileDaAprire = new FileInfo(NomeFile); /*CmsSignedData Firmato; * if (GiaFirmato) { * CmsSignedData signedData = new CmsSignedData(File.ReadAllBytes(NomeFile)); * if (signedData!=null){ * SignerInformationStore signers = signedData.GetSignerInfos(); * certList.Add(signers.GetSigners()); * //MessageBox.Show(signedData.ContentInfo.GetEncoded().Length.ToString()); * //signedData.ContentInfo.GetEncoded(); * } * certList.Insert(0,certCopy); * CmsProcessableByteArray file = new CmsProcessableByteArray(signedData.ContentInfo.GetEncoded()); * Firmato = cms.Generate(file, true); * } else { * certList.Add(certCopy); * CmsProcessableFile file = new CmsProcessableFile(FileDaAprire); * Firmato = cms.Generate(file, true); * } */ CmsProcessableFile file = new CmsProcessableFile(FileDaAprire); CmsSignedData Firmato = cms.Generate(file, true); byte[] Encoded = Firmato.GetEncoded(); if (UsaTSA) { CmsSignedData sd = new CmsSignedData(Encoded); SignerInformationStore signers = sd.GetSignerInfos(); byte[] signature = null; SignerInformation signer = null; foreach (SignerInformation signer_ in signers.GetSigners()) { signer = signer_; break; } signature = signer.GetSignature(); Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature, TSAurl, TSAuser, TSApass)); signer = SignerInformation.ReplaceUnsignedAttributes(signer, at); IList signerInfos = new ArrayList(); signerInfos.Add(signer); sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos)); Encoded = sd.GetEncoded(); } RisFirma = ""; return(Encoded); } catch (Exception ex) { RisFirma = ex.ToString(); return(null); } }
/// <exception cref="System.IO.IOException"></exception> public virtual byte[] GetArchiveTimestampData(int index, Document originalDocument ) { ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); BcCms.ContentInfo contentInfo = cmsSignedData.ContentInfo; BcCms.SignedData signedData = BcCms.SignedData.GetInstance(contentInfo.Content); // 5.4.1 if (signedData.EncapContentInfo == null || signedData.EncapContentInfo. Content == null) { if (originalDocument != null) { //jbonilla Hack para leer un InputStream en su totalidad. toTimestamp.Write(Streams.ReadAll( originalDocument.OpenStream())); } else { throw new RuntimeException("Signature is detached and no original data provided." ); } } else { BcCms.ContentInfo content = signedData.EncapContentInfo; DerOctetString octet = (DerOctetString)content.Content; BcCms.ContentInfo info2 = new BcCms.ContentInfo(new DerObjectIdentifier("1.2.840.113549.1.7.1" ), new BerOctetString(octet.GetOctets())); toTimestamp.Write(info2.GetEncoded()); } if (signedData.Certificates != null) { DerOutputStream output = new DerOutputStream(toTimestamp); output.WriteObject(signedData.Certificates); output.Close(); } if (signedData.CRLs != null) { toTimestamp.Write(signedData.CRLs.GetEncoded()); } if (signerInformation.UnsignedAttributes != null) { Asn1EncodableVector original = signerInformation.UnsignedAttributes.ToAsn1EncodableVector (); IList <BcCms.Attribute> timeStampToRemove = GetTimeStampToRemove(index); Asn1EncodableVector filtered = new Asn1EncodableVector(); for (int i = 0; i < original.Count; i++) { Asn1Encodable enc = original[i]; if (!timeStampToRemove.Contains(enc)) { filtered.Add(original[i]); } } SignerInformation filteredInfo = SignerInformation.ReplaceUnsignedAttributes(signerInformation , new BcCms.AttributeTable(filtered)); toTimestamp.Write(filteredInfo.ToSignerInfo().GetEncoded()); } return(toTimestamp.ToByteArray()); }