private void VerifySignatures(CmsSignedData s, byte[] contentDigest) { IX509Store x509Certs = s.GetCertificates("Collection"); IX509Store x509Crls = s.GetCrls("Collection"); SignerInformationStore signers = s.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate)certEnum.Current; VerifySigner(signer, cert); if (contentDigest != null) { Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest())); } } ICollection certColl = x509Certs.GetMatches(null); ICollection crlColl = x509Crls.GetMatches(null); Assert.AreEqual(certColl.Count, s.GetCertificates("Collection").GetMatches(null).Count); Assert.AreEqual(crlColl.Count, s.GetCrls("Collection").GetMatches(null).Count); }
public SignerInformationStore GetSignerInfos() { if (_signerInfoStore == null) { PopulateCertCrlSets(); IList list = Platform.CreateArrayList(); IDictionary dictionary = Platform.CreateHashtable(); foreach (object key in _digests.Keys) { dictionary[key] = DigestUtilities.DoFinal((IDigest)_digests[key]); } try { Asn1SetParser signerInfos = _signedData.GetSignerInfos(); IAsn1Convertible asn1Convertible; while ((asn1Convertible = signerInfos.ReadObject()) != null) { SignerInfo instance = SignerInfo.GetInstance(asn1Convertible.ToAsn1Object()); string digestAlgName = Helper.GetDigestAlgName(instance.DigestAlgorithm.Algorithm.Id); byte[] digest = (byte[])dictionary[digestAlgName]; list.Add(new SignerInformation(instance, _signedContentType, null, new BaseDigestCalculator(digest))); } } catch (IOException ex) { throw new CmsException("io exception: " + ex.Message, ex); } _signerInfoStore = new SignerInformationStore(list); } return(_signerInfoStore); }
private SignerInformation GetFirstSignerInfo(SignerInformationStore store) { IEnumerator e = store.GetSigners().GetEnumerator(); e.MoveNext(); return((SignerInformation)e.Current); }
public static bool ValidateSignature(byte[] messageBytes, byte[] signatureBytes, X509Certificate certificate) { CmsProcessable signedContent = new CmsProcessableByteArray(messageBytes); CmsSignedData signedData = new CmsSignedData(signedContent, signatureBytes); IX509Store certificateStore = signedData.GetCertificates("Collection"); SignerInformationStore signerInfoStore = signedData.GetSignerInfos(); ICollection signers = signerInfoStore.GetSigners(); foreach (SignerInformation signer in signers) { bool isChainValid = ValidateCertificateChain(certificateStore, signer.SignerID); if (!isChainValid) { return(false); } bool verified = signer.Verify(certificate); if (!verified) { return(false); } } return(true); }
public static CmsSignedData ReplaceSigners(CmsSignedData signedData, SignerInformationStore signerInformationStore) { CmsSignedData cmsSignedData = new CmsSignedData(signedData); cmsSignedData.signerInfoStore = signerInformationStore; Asn1EncodableVector asn1EncodableVector = new Asn1EncodableVector(); Asn1EncodableVector asn1EncodableVector2 = new Asn1EncodableVector(); foreach (SignerInformation signer in signerInformationStore.GetSigners()) { asn1EncodableVector.Add(Helper.FixAlgID(signer.DigestAlgorithmID)); asn1EncodableVector2.Add(signer.ToSignerInfo()); } Asn1Set asn1Set = new DerSet(asn1EncodableVector); Asn1Set asn1Set2 = new DerSet(asn1EncodableVector2); Asn1Sequence asn1Sequence = (Asn1Sequence)signedData.signedData.ToAsn1Object(); asn1EncodableVector2 = new Asn1EncodableVector(asn1Sequence[0], asn1Set); for (int i = 2; i != asn1Sequence.Count - 1; i++) { asn1EncodableVector2.Add(asn1Sequence[i]); } asn1EncodableVector2.Add(asn1Set2); cmsSignedData.signedData = SignedData.GetInstance(new BerSequence(asn1EncodableVector2)); cmsSignedData.contentInfo = new ContentInfo(cmsSignedData.contentInfo.ContentType, cmsSignedData.signedData); return(cmsSignedData); }
private CmsSignedData(CmsSignedData c) { signedData = c.signedData; contentInfo = c.contentInfo; signedContent = c.signedContent; signerInfoStore = c.signerInfoStore; }
/// <param name="signedData"></param> /// <returns></returns> public virtual CmsSignedData ExtendCMSSignedData(CmsSignedData signedData, Document originalData, SignatureParameters parameters) { SignerInformationStore signerStore = signedData.GetSignerInfos(); List <SignerInformation> siArray = new List <SignerInformation>(); //Iterator<SignerInformation> infos = signerStore.GetSigners().Iterator(); IEnumerator infos = signerStore.GetSigners().GetEnumerator(); while (infos.MoveNext()) { SignerInformation si = (SignerInformation)infos.Current; try { siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData)); } catch (IOException) { //LOG.Error("Exception when extending signature"); siArray.Add(si); } } SignerInformationStore newSignerStore = new SignerInformationStore(siArray); return(CmsSignedData.ReplaceSigners(signedData, newSignerStore)); }
public static void ReadXmlSigned(this Fattura fattura, Stream stream, bool validateSignature = true) { CmsSignedData signedFile = new CmsSignedData(stream); if (validateSignature) { IX509Store certStore = signedFile.GetCertificates("Collection"); ICollection certs = certStore.GetMatches(new X509CertStoreSelector()); SignerInformationStore signerStore = signedFile.GetSignerInfos(); ICollection signers = signerStore.GetSigners(); foreach (object tempCertification in certs) { Org.BouncyCastle.X509.X509Certificate certification = tempCertification as Org.BouncyCastle.X509.X509Certificate; foreach (object tempSigner in signers) { SignerInformation signer = tempSigner as SignerInformation; if (!signer.Verify(certification.GetPublicKey())) { throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.SignatureException); } } } } using (var memoryStream = new MemoryStream()) { signedFile.SignedContent.Write(memoryStream); fattura.ReadXml(memoryStream); } }
public void AddSigners(SignerInformationStore signerStore) { foreach (SignerInformation signer in signerStore.GetSigners()) { _signers.Add(signer); AddSignerCallback(signer); } }
private static SignerInformation GetFirstSignerInfo(SignerInformationStore store) { var signers = store.GetSigners(); var enumerator = signers.GetEnumerator(); enumerator.MoveNext(); return((SignerInformation)enumerator.Current); }
// 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); } }
private byte[] TimestampAuthorityResponse(EstEIDReader estEidReader, byte[] signedPkcs) { ArrayList newSigners = new ArrayList(); CmsSignedData sd = new CmsSignedData(signedPkcs); foreach (SignerInformation si in sd.GetSignerInfos().GetSigners()) { // possible TSA URLs //string TsaServerUrl = "http://www.edelweb.fr/cgi-bin/service-tsp"; //string TsaServerUrl = "http://dse200.ncipher.com/TSS/HttpTspServer"; byte[] signedDigest = si.GetSignature(); byte[] timeStampHash = ComputeHash(estEidReader, signedDigest); string TsaServerUrl = stamp.Url; string TsaUser = stamp.User; string TsaPassword = stamp.Password; string error = string.Empty; byte[] timeStampToken = X509Utils.GetTimestampToken(TsaServerUrl, TsaUser, TsaPassword, timeStampHash, ref error); if (timeStampToken == null) { throw new Exception(Resources.TSA_ERROR + error); } Hashtable ht = new Hashtable(); Asn1Object derObj = new Asn1InputStream(timeStampToken).ReadObject(); DerSet derSet = new DerSet(derObj); Org.BouncyCastle.Asn1.Cms.Attribute unsignAtt = new Org.BouncyCastle.Asn1.Cms.Attribute( new DerObjectIdentifier(X509Utils.ID_TIME_STAMP_TOKEN), derSet); ht.Add(X509Utils.ID_TIME_STAMP_TOKEN, unsignAtt); Org.BouncyCastle.Asn1.Cms.AttributeTable unsignedAtts = new Org.BouncyCastle.Asn1.Cms.AttributeTable(ht); newSigners.Add(SignerInformation.ReplaceUnsignedAttributes(si, unsignedAtts)); } SignerInformationStore newSignerInformationStore = new SignerInformationStore(newSigners); CmsSignedData newSd = CmsSignedData.ReplaceSigners(sd, newSignerInformationStore); // Encode the CMS/PKCS #7 message return(newSd.GetEncoded()); }
public static SignerInformation GetSignerInfoByEnumeration(SignerInformationStore signerInformationStore, SignerID id) { SignerInformation si = null; foreach (SignerInformation s in signerInformationStore.GetSigners()) { if (s.SignerID == id) { si = s; break; } } return(si); }
static void Main(string[] args) { //if (args.Length > 0) //string fullFileName = Path.GetFullPath(args[0]); foreach (string fileName in Directory.GetFiles("p7m")) { FileStream file = new FileStream(fileName, FileMode.Open); bool isValid = true; Console.WriteLine("File to decrypt: " + fileName); try { CmsSignedData signedFile = new CmsSignedData(file); IX509Store certStore = signedFile.GetCertificates("Collection"); ICollection certs = certStore.GetMatches(new X509CertStoreSelector()); SignerInformationStore signerStore = signedFile.GetSignerInfos(); ICollection signers = signerStore.GetSigners(); foreach (object tempCertification in certs) { X509Certificate certification = tempCertification as X509Certificate; foreach (object tempSigner in signers) { SignerInformation signer = tempSigner as SignerInformation; if (!signer.Verify(certification.GetPublicKey())) { isValid = false; break; } } } string newFileName = Path.Combine(Directory.CreateDirectory("p7m-extracted").Name, Path.GetFileNameWithoutExtension(fileName)); using (var fileStream = new FileStream(newFileName, FileMode.Create, FileAccess.Write)) { signedFile.SignedContent.Write(fileStream); Console.WriteLine("File decrypted: " + newFileName); } } catch (Exception ex) { isValid = false; } Console.WriteLine("File valid: " + isValid); ; } Console.ReadLine(); }
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())); }
/// <summary> /// Método que busca en las demás firmas el tipo de contenido firmado /// </summary> /// <param name="siStore"></param> /// <returns></returns> private BcCms.Attribute GetContentHintAttribute(SignerInformationStore siStore) { var signers = siStore.GetSigners(); foreach (SignerInformation signerInfo in signers) { BcCms.Attribute contentHint = signerInfo.SignedAttributes[PkcsObjectIdentifiers.IdAAContentHint]; if (contentHint != null) { return(contentHint); } } return(null); }
public void TestAttributeGenerators() { IList certList = new ArrayList(); MemoryStream bOut = new MemoryStream(); certList.Add(OrigCert); certList.Add(SignCert); IX509Store x509Certs = X509StoreFactory.Create( "Certificate/Collection", new X509CollectionStoreParameters(certList)); CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); CmsAttributeTableGenerator signedGen = new SignedGenAttributeTableGenerator(); CmsAttributeTableGenerator unsignedGen = new UnsignedGenAttributeTableGenerator(); gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1, signedGen, unsignedGen); gen.AddCertificates(x509Certs); Stream sigOut = gen.Open(bOut, true); byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage); sigOut.Write(testBytes, 0, testBytes.Length); sigOut.Close(); CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray()); sp.GetSignedContent().Drain(); VerifySignatures(sp); // // check attributes // SignerInformationStore signers = sp.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { checkAttribute(signer.GetContentDigest(), signer.SignedAttributes[dummyOid1]); checkAttribute(signer.GetSignature(), signer.UnsignedAttributes[dummyOid2]); } }
private SignerInformation ExtractSignerInfo(CmsSignedDataParser parser) { //Extract the signer info SignerInformationStore signerInfoStore = parser.GetSignerInfos(); if (signerInfoStore.Count != 1) { #if NETFRAMEWORK trace.TraceEvent(TraceEventType.Error, 0, "The message to complete does not contain a single signature"); #else logger.LogError("The message to complete does not contain a single signature"); #endif throw new InvalidMessageException("The message does not contain a single signature"); } return(signerInfoStore.GetSigners().Cast <SignerInformation>().First()); }
/// <summary> /// Método que busca en las demás firmas el message-digest que coincida con el algoritmo de huella dado /// </summary> /// <param name="siStore"></param> /// <param name="digestMethod"></param> /// <returns></returns> private byte[] GetDigestValue(SignerInformationStore siStore, DigestMethod digestMethod) { var signers = siStore.GetSigners(); foreach (SignerInformation signerInfo in signers) { if (signerInfo.DigestAlgOid == digestMethod.Oid) { BcCms.Attribute digest = signerInfo.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest]; DerOctetString derHash = (DerOctetString)digest.AttrValues[0]; return(derHash.GetOctets()); } } return(null); }
/// <summary> /// Validate the signature that valid or not /// </summary> /// <param name="signedData"></param> /// <param name="certificate"></param> private void validateSignature(CmsSignedData signedData, X509Certificate2 certificate) { bool isValid = false; SignerInformationStore signers = signedData.GetSignerInfos(); IEnumerator it = signers.GetSigners().GetEnumerator(); if (it.MoveNext()) { SignerInformation signer = (SignerInformation)it.Current; Org.BouncyCastle.X509.X509Certificate cer = DotNetUtilities.FromX509Certificate(certificate); isValid = signer.Verify(cer); } if (!isValid) { throw new Exception("Signature is not valid"); } }
// taken from bouncy castle SignedDataTest.cs private static bool VerifySignatures( CmsSignedData sp) { var signaturesValid = true; IX509Store x509Certs = sp.GetCertificates("Collection"); SignerInformationStore signers = sp.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)certEnum.Current; signaturesValid &= signer.Verify(cert); } return(signaturesValid); }
public static byte[] getHashFromSignature(byte[] signature) { CmsSignedData content = new CmsSignedData(signature); byte[] retval = null; try { SignerInformationStore sistore = content.GetSignerInfos(); foreach (SignerInformation signer in sistore.GetSigners()) { if (signer.SignedAttributes != null) { if (signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtMessageDigest] != null) { Asn1Encodable enc = signer.SignedAttributes[Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.Pkcs9AtMessageDigest].AttrValues[0]; retval = Org.BouncyCastle.Asn1.Asn1OctetString.GetInstance(enc).GetOctets(); } } else { IX509Store store = content.GetCertificates("Collection"); ICollection certsColl = store.GetMatches(null); foreach (Org.BouncyCastle.X509.X509Certificate cert in certsColl) { signer.Verify(cert); retval = signer.GetContentDigest(); break; } } if (retval != null) { return(retval); } } } catch { return(getSha256(extractSignedContent(signature))); } return(null); }
/// <exception cref="System.IO.IOException"></exception> public virtual Document ExtendSignatures(Document document, Document originalData , SignatureParameters parameters) { try { CmsSignedData signedData = new CmsSignedData(document.OpenStream()); SignerInformationStore signerStore = signedData.GetSignerInfos(); List <SignerInformation> siArray = new List <SignerInformation>(); foreach (SignerInformation si in signerStore.GetSigners()) { try { //jbonilla - Hack para evitar errores cuando una firma ya ha sido extendida. //Se asume que sólo se extiende las firmas desde BES. //TODO jbonilla - Se debería validar hasta qué punto se extendió (BES, T, C, X, XL). if (si.UnsignedAttributes.Count == 0) { siArray.Add(ExtendCMSSignature(signedData, si, parameters, originalData)); } else { //LOG.Error("Already extended?"); siArray.Add(si); } } catch (IOException) { //LOG.Error("Exception when extending signature"); siArray.Add(si); } } SignerInformationStore newSignerStore = new SignerInformationStore(siArray); CmsSignedData extended = CmsSignedData.ReplaceSigners(signedData, newSignerStore); return(new InMemoryDocument(extended.GetEncoded())); } catch (CmsException) { throw new IOException("Cannot parse CMS data"); } }
public static Stream ReplaceSigners(Stream original, SignerInformationStore signerInformationStore, Stream outStr) { CmsSignedDataStreamGenerator cmsSignedDataStreamGenerator = new CmsSignedDataStreamGenerator(); CmsSignedDataParser cmsSignedDataParser = new CmsSignedDataParser(original); cmsSignedDataStreamGenerator.AddSigners(signerInformationStore); CmsTypedStream signedContent = cmsSignedDataParser.GetSignedContent(); bool flag = signedContent != null; Stream stream = cmsSignedDataStreamGenerator.Open(outStr, cmsSignedDataParser.SignedContentType.Id, flag); if (flag) { Streams.PipeAll(signedContent.ContentStream, stream); } cmsSignedDataStreamGenerator.AddAttributeCertificates(cmsSignedDataParser.GetAttributeCertificates("Collection")); cmsSignedDataStreamGenerator.AddCertificates(cmsSignedDataParser.GetCertificates("Collection")); cmsSignedDataStreamGenerator.AddCrls(cmsSignedDataParser.GetCrls("Collection")); Platform.Dispose(stream); return(outStr); }
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); }
public void TestSignHashWithBouncyCastle() { byte[] hashBytes = System.Convert.FromBase64String(Base64encodedHashToSign); byte[] signedCmsData = SignatureProvider.SignatureProvider.Sign(hashBytes, SignerName, SignerEmail, SignerCountry, SignerOrganization); CmsSignedData cmsSignedData = new CmsSignedData(signedCmsData); IX509Store x509Certs = cmsSignedData.GetCertificates("Collection"); SignerInformationStore signers = cmsSignedData.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); Assert.AreEqual(1, certCollection.Count); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate)certEnum.Current; Assert.AreEqual(cert.SubjectDN.ToString(), "CN=Cyril Thirion,E=cyril.thirion\\[email protected],C=FR,O=Acme"); Assert.AreEqual(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtContentType].AttrValues[0].ToString(), PkcsObjectIdentifiers.Data.ToString()); Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest]); Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.IdAASigningCertificateV2]); Assert.IsNotNull(signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtSigningTime]); Assert.AreEqual( "#" + BitConverter.ToString(hashBytes).Replace("-", ""), signer.SignedAttributes[PkcsObjectIdentifiers.Pkcs9AtMessageDigest].AttrValues[0].ToString(), true ); byte[] signedData = signer.GetEncodedSignedAttributes(); System.IO.File.WriteAllBytes("/tmp/tmp.txt", signedData); ISigner s = SignerUtilities.GetSigner("SHA256withRSA"); s.Init(false, cert.GetPublicKey()); s.BlockUpdate(signedData, 0, signedData.Length); Assert.IsTrue(s.VerifySignature(signer.GetSignature()), "Signature verification failed."); } }
/// <summary> /// The method used to verify signature. /// </summary> /// <param name="sp"></param> /// <returns></returns> public static bool VerifySignatures(CmsSignedDataParser sp) { List <bool> result = new List <bool>(); IX509Store x509Certs = sp.GetCertificates("Collection"); SignerInformationStore signerInfos = sp.GetSignerInfos(); var signers = signerInfos.GetSigners(); foreach (SignerInformation signer in signers) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); foreach (Org.BouncyCastle.X509.X509Certificate cert in certCollection) { var isValid = signer.Verify(cert); if (!isValid) { throw new Exception("Certificate verification error, the signer could not be verified."); } result.Add(isValid); } } return(result.TrueForAll(m => m == true)); }
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())); }
private void VerifySignatures(CmsSignedDataParser sp) { CmsTypedStream sc = sp.GetSignedContent(); if (sc != null) { sc.Drain(); } IX509Store x509Certs = sp.GetCertificates("Collection"); SignerInformationStore signers = sp.GetSignerInfos(); foreach (SignerInformation signer in signers.GetSigners()) { ICollection certCollection = x509Certs.GetMatches(signer.SignerID); IEnumerator certEnum = certCollection.GetEnumerator(); certEnum.MoveNext(); X509Certificate cert = (X509Certificate)certEnum.Current; VerifySigner(signer, cert); } }
public static void ReadXmlSigned(this Fattura fattura, string filePath) { CmsSignedData signedFile = new CmsSignedData(new FileStream(filePath, FileMode.Open, FileAccess.Read)); IX509Store certStore = signedFile.GetCertificates("Collection"); ICollection certs = certStore.GetMatches(new X509CertStoreSelector()); SignerInformationStore signerStore = signedFile.GetSignerInfos(); ICollection signers = signerStore.GetSigners(); foreach (object tempCertification in certs) { Org.BouncyCastle.X509.X509Certificate certification = tempCertification as Org.BouncyCastle.X509.X509Certificate; foreach (object tempSigner in signers) { SignerInformation signer = tempSigner as SignerInformation; if (!signer.Verify(certification.GetPublicKey())) { throw new FatturaElettronicaSignatureException(Resources.ErrorMessages.SignatureException); } } } string outFile = Path.GetTempFileName(); using (var fileStream = new FileStream(outFile, FileMode.Create, FileAccess.Write)) { signedFile.SignedContent.Write(fileStream); } using (var r = XmlReader.Create(outFile, new XmlReaderSettings { IgnoreWhitespace = true, IgnoreComments = true })) { fattura.ReadXml(r); } }
private SignerInformation GetFirstSignerInfo(SignerInformationStore store) { IEnumerator e = store.GetSigners().GetEnumerator(); e.MoveNext(); return (SignerInformation)e.Current; }