// Sign the message with the private key of the signer. static public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached, bool UsaTSA, string TSAurl, string TSAuser, string TSApass) { try { SHA256Managed hashSha256 = new SHA256Managed(); byte[] certHash = hashSha256.ComputeHash(signerCert.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)signerCert.PrivateKey; Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(signerCert); 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); CmsProcessableByteArray file = new CmsProcessableByteArray(msg); //CmsProcessableFile(File); CmsSignedData Firmato = cms.Generate(file, false); //se settato a true, il secondo argomento integra l'intero file byte[] bb = Firmato.GetEncoded(); if (UsaTSA) { CmsSignedData sd = new CmsSignedData(bb); 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)); bb = sd.GetEncoded(); } return(bb); } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(null); } }
/// <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); DerObjectIdentifier attributeId = null; ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); 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: { throw new InvalidOperationException("CAdES-X Profile: Extended validation is set but no valid type (1 or 2)" ); } } 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()); //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); IDictionary unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); BcCms.Attribute extendedTimeStamp = GetTimeStampAttribute(attributeId, GetSignatureTsa( ), digestAlgorithm, toTimestamp.ToByteArray()); //unsignedAttrHash.Put(attributeId, extendedTimeStamp); unsignedAttrHash.Add(attributeId, extendedTimeStamp); return(SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable(unsignedAttrHash ))); }
/** * Fetches the signature time-stamp attributes from a SignerInformation object. * Checks that the MessageImprint for each time-stamp matches the signature field. * (see RFC 3161 Appendix A). * * @param signerInfo a SignerInformation to search for time-stamps * @return a collection of TimeStampToken objects * @throws TSPValidationException */ public static ICollection GetSignatureTimestamps( SignerInformation signerInfo) { IList timestamps = Platform.CreateArrayList(); AttributeTable unsignedAttrs = signerInfo.UnsignedAttributes; if (unsignedAttrs != null) { foreach (Attribute tsAttr in unsignedAttrs.GetAll( PkcsObjectIdentifiers.IdAASignatureTimeStampToken)) { foreach (Asn1Encodable asn1 in tsAttr.AttrValues) { try { ContentInfo contentInfo = ContentInfo.GetInstance( asn1.ToAsn1Object()); TimeStampToken timeStampToken = new TimeStampToken(contentInfo); TimeStampTokenInfo tstInfo = timeStampToken.TimeStampInfo; byte[] expectedDigest = DigestUtilities.CalculateDigest( GetDigestAlgName(tstInfo.MessageImprintAlgOid), signerInfo.GetSignature()); if (!Arrays.ConstantTimeAreEqual(expectedDigest, tstInfo.GetMessageImprintDigest())) { throw new TspValidationException("Incorrect digest in message imprint"); } timestamps.Add(timeStampToken); } catch (SecurityUtilityException) { throw new TspValidationException("Unknown hash algorithm specified in timestamp"); } catch (Exception) { throw new TspValidationException("Timestamp could not be parsed"); } } } } return(timestamps); }
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))); } }
/// <exception cref="System.IO.IOException"></exception> protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData , SignerInformation si, SignatureParameters parameters, Document originalData) { if (this.signatureTsa == null) { throw new ConfigurationException(ConfigurationException.MSG.CONFIGURE_TSP_SERVER); } //LOG.Info("Extend signature with id " + si.SignerID); BcCms.AttributeTable unsigned = si.UnsignedAttributes; //IDictionary<DerObjectIdentifier, Attribute> unsignedAttrHash = null; IDictionary unsignedAttrHash = null; if (unsigned == null) { unsignedAttrHash = new Dictionary <DerObjectIdentifier, Attribute>(); } else { unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); } //TODO jbonilla - ¿Qué ocurre si ya es CAdES-T? No se debería volver a extender. Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken , this.signatureTsa, digestAlgorithm, si.GetSignature()); //unsignedAttrHash.Put(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp); unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable (unsignedAttrHash)); return(newsi); }
public static global::System.Collections.ICollection GetSignatureTimestamps(SignerInformation signerInfo) { global::System.Collections.IList list = Platform.CreateArrayList(); Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInfo.UnsignedAttributes; if (unsignedAttributes != null) { global::System.Collections.IEnumerator enumerator = unsignedAttributes.GetAll(PkcsObjectIdentifiers.IdAASignatureTimeStampToken).GetEnumerator(); try { while (enumerator.MoveNext()) { Attribute attribute = (Attribute)enumerator.get_Current(); { global::System.Collections.IEnumerator enumerator2 = attribute.AttrValues.GetEnumerator(); try { while (enumerator2.MoveNext()) { Asn1Encodable asn1Encodable = (Asn1Encodable)enumerator2.get_Current(); try { Org.BouncyCastle.Asn1.Cms.ContentInfo instance = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(asn1Encodable.ToAsn1Object()); TimeStampToken timeStampToken = new TimeStampToken(instance); TimeStampTokenInfo timeStampInfo = timeStampToken.TimeStampInfo; byte[] a = DigestUtilities.CalculateDigest(GetDigestAlgName(timeStampInfo.MessageImprintAlgOid), signerInfo.GetSignature()); if (!Arrays.ConstantTimeAreEqual(a, timeStampInfo.GetMessageImprintDigest())) { throw new TspValidationException("Incorrect digest in message imprint"); } list.Add((object)timeStampToken); } catch (SecurityUtilityException) { throw new TspValidationException("Unknown hash algorithm specified in timestamp"); } catch (global::System.Exception) { throw new TspValidationException("Timestamp could not be parsed"); } } } finally { global::System.IDisposable disposable2 = enumerator2 as global::System.IDisposable; if (disposable2 != null) { disposable2.Dispose(); } } } } return((global::System.Collections.ICollection)list); } finally { global::System.IDisposable disposable = enumerator as global::System.IDisposable; if (disposable != null) { disposable.Dispose(); } } } return((global::System.Collections.ICollection)list); }
/** * generate a set of one or more SignerInformation objects representing counter signatures on * the passed in SignerInformation object. * * @param signer the signer to be countersigned * @param sigProvider the provider to be used for counter signing. * @return a store containing the signers. */ public SignerInformationStore GenerateCounterSigners( SignerInformation signer) { return(this.Generate(null, new CmsProcessableByteArray(signer.GetSignature()), false).GetSignerInfos()); }
public virtual byte[] GetSignatureTimestampData() { return(signerInformation.GetSignature()); }
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(); }
protected internal override SignerInformation ExtendCMSSignature(CmsSignedData signedData, SignerInformation si, SignatureParameters parameters, Document originalData) { if (si is null) { throw new System.ArgumentNullException(nameof(si)); } if (SignatureTsa == null) { throw new System.ArgumentNullException(nameof(SignatureTsa)); } logger.Info("Extend signature with id " + si.SignerID); BcCms.AttributeTable unsigned = si.UnsignedAttributes; IDictionary unsignedAttrHash; if (unsigned is null) { unsignedAttrHash = new Dictionary <DerObjectIdentifier, Attribute>(); } else { unsignedAttrHash = si.UnsignedAttributes.ToDictionary(); } //TODO: jbonilla - What happens if it is already CAdES-T? It should not be extended again. Attribute signatureTimeStamp = GetTimeStampAttribute(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, SignatureTsa, si.GetSignature()); unsignedAttrHash.Add(PkcsObjectIdentifiers.IdAASignatureTimeStampToken, signatureTimeStamp); SignerInformation newsi = SignerInformation.ReplaceUnsignedAttributes(si, new BcCms.AttributeTable (unsignedAttrHash)); return(newsi); }
public static ICollection GetSignatureTimestamps(SignerInformation signerInfo) { IList list = Platform.CreateArrayList(); Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAttributes = signerInfo.UnsignedAttributes; if (unsignedAttributes != null) { foreach (Org.BouncyCastle.Asn1.Cms.Attribute attribute in unsignedAttributes.GetAll(PkcsObjectIdentifiers.IdAASignatureTimeStampToken)) { foreach (Asn1Encodable asn1Encodable in attribute.AttrValues) { try { Org.BouncyCastle.Asn1.Cms.ContentInfo instance = Org.BouncyCastle.Asn1.Cms.ContentInfo.GetInstance(asn1Encodable.ToAsn1Object()); TimeStampToken timeStampToken = new TimeStampToken(instance); TimeStampTokenInfo timeStampInfo = timeStampToken.TimeStampInfo; byte[] a = DigestUtilities.CalculateDigest(TspUtil.GetDigestAlgName(timeStampInfo.MessageImprintAlgOid), signerInfo.GetSignature()); if (!Arrays.ConstantTimeAreEqual(a, timeStampInfo.GetMessageImprintDigest())) { throw new TspValidationException("Incorrect digest in message imprint"); } list.Add(timeStampToken); } catch (SecurityUtilityException) { throw new TspValidationException("Unknown hash algorithm specified in timestamp"); } catch (Exception) { throw new TspValidationException("Timestamp could not be parsed"); } } } } return(list); }
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); } }