Exemplo n.º 1
0
        public void SignAndVerify()
        {
            var xml = new XmlDocument();

            xml.LoadXml(
                @"<sbdh:StandardBusinessDocument xmlns:sbdh=""http://eessi.dgempl.ec.europa.eu/namespaces/sbdh"">
                    <sbdh:StandardBusinessDocumentHeader>
                    </sbdh:StandardBusinessDocumentHeader>
                    <sed:StructuredElectronicDocument xmlns:sed=""http://ec.europa.eu/eessi/ns/sed"">
                    </sed:StructuredElectronicDocument>
                </sbdh:StandardBusinessDocument>");

            var xadesSigner = new XadesSigner
            {
                Certificate = Certificates.CreateSelfSigned(),
                Xml         = xml
            };

            xadesSigner.Sign();

            var xadesVerifier = new XadesVerifier
            {
                Xml = xml
            };
            var isSignatureCorrect = xadesVerifier.Verify();

            Assert.IsTrue(isSignatureCorrect);
        }
Exemplo n.º 2
0
        public void VerifierVerifyParam1Null()
        {
            var xerifer = new XadesVerifier();


            Assert.Throws <ArgumentNullException>(() => xerifer.Verify(null, null));
        }
Exemplo n.º 3
0
        public void XadesT()
        {
            X509Certificate2 sign;

            using (var readers = new Readers(ReaderScope.User))
                using (var store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
                {
                    var target = (EidCard)readers.ListCards().Where(c => c is EidCard).FirstOrDefault();
                    Assert.True(target != null, "No eid inserted, please insert (test) eid");
                    target.Open();

                    store.Open(OpenFlags.ReadOnly);
                    sign = store.Certificates.Find(X509FindType.FindByThumbprint, target.SignCert.Thumbprint, false)[0];
                }

            var document = new XmlDocument();

            document.PreserveWhitespace = true;
            document.Load(@"data\basic.xml");
            var xsigner = new XadesCreator(sign, true);

            xsigner.TimestampProvider = new Rfc3161TimestampProvider();
            var xades = xsigner.CreateXadesT(document, "_1");

            document.DocumentElement.AppendChild(xades);

            // Output for reading
            MemoryStream stream = new MemoryStream();

            using (var writer = XmlWriter.Create(stream))
            {
                document.WriteTo(writer);
            }
            stream.Seek(0, SeekOrigin.Begin);

            var signed = new XmlDocument();

            signed.PreserveWhitespace = true;
            signed.Load(stream);

            var xerifier = new XadesVerifier();
            var info     = xerifier.Verify(signed, (XmlElement)XadesTools.FindXadesProperties(signed)[0]);

            Assert.NotNull(info);
            Assert.NotNull(info.Certificate);
            Assert.Equal(sign, info.Certificate);
            Assert.Equal(XadesForm.XadesBes, info.Form);
            Assert.NotNull(info.Time);
            Assert.True((DateTimeOffset.Now - info.Time.Value) < new TimeSpan(0, 5, 0));
        }
Exemplo n.º 4
0
        public void RoundTestXadesTViaFedict()
        {
            var xigner = new XadesCreator(sign, true, extraCerts);

            xigner.TimestampProvider = new Rfc3161TimestampProvider();
            xigner.DataTransforms.Add(new XmlDsigBase64Transform());
            xigner.DataTransforms.Add(new OptionalDeflateTransform());
            var xades = xigner.CreateXadesT(document, "_D4840C96-8212-491C-9CD9-B7144C1AD450");

            //Output for debugging
            var xml            = new StringBuilder();
            var writerSettings = new XmlWriterSettings
            {
                Indent = true
            };

            using (var writer = XmlWriter.Create(xml, writerSettings))
            {
                xades.WriteTo(writer);
            }
            System.Console.WriteLine(xml.ToString());

            //Output for reading
            MemoryStream stream = new MemoryStream();

            using (var writer = XmlWriter.Create(stream))
            {
                xades.WriteTo(writer);
            }
            stream.Seek(0, SeekOrigin.Begin);

            var xades2 = new XmlDocument();

            xades2.PreserveWhitespace = true;
            xades2.Load(stream);

            var xerifier = new XadesVerifier();
            var info     = xerifier.Verify(document, (XmlElement)XadesTools.FindXadesProperties(xades2)[0]);

            Assert.NotNull(info);
            Assert.NotNull(info.Certificate);
            Assert.Equal(sign, info.Certificate);
            Assert.Equal(XadesForm.XadesBes | XadesForm.XadesT, info.Form);
            Assert.NotNull(info.Time);
            Assert.True((DateTimeOffset.Now - info.Time.Value) < new TimeSpan(0, 5, 0));
            Assert.Empty(info.ManifestResult);
        }
Exemplo n.º 5
0
        public void RountTestXadesTFullDoc()
        {
            var xigner = new XadesCreator(sign, true, extraCerts);

            xigner.TimestampProvider = new EHealthTimestampProvider(tsa);

            var xades = xigner.CreateXadesT(document);

            var xml            = new StringBuilder();
            var writerSettings = new XmlWriterSettings
            {
                Indent = true
            };

            using (var writer = XmlWriter.Create(xml, writerSettings))
            {
                xades.WriteTo(writer);
            }
            System.Console.WriteLine(xml.ToString());

            MemoryStream stream = new MemoryStream();

            using (var writer = XmlWriter.Create(stream))
            {
                xades.WriteTo(writer);
            }
            stream.Seek(0, SeekOrigin.Begin);

            var xades2 = new XmlDocument();

            xades2.PreserveWhitespace = true;
            xades2.Load(stream);

            var xerifier = new XadesVerifier();
            var info     = xerifier.Verify(document, (XmlElement)XadesTools.FindXadesProperties(xades2)[0]);

            Assert.NotNull(info);
            Assert.NotNull(info.Certificate);
            Assert.Equal(sign, info.Certificate);
            Assert.Equal(XadesForm.XadesBes | XadesForm.XadesT, info.Form);
            Assert.NotNull(info.Time);
            Assert.True((DateTimeOffset.Now - info.Time.Value) < new TimeSpan(0, 5, 0));
            Assert.Empty(info.ManifestResult);
        }
Exemplo n.º 6
0
        private void DoTest(GenericAsyncClient client, TimeStampAuthorityClient tsaClient)
        {
            //Create common input with info about the requestor, must match SAML
            CommonInputType commonInput = new CommonInputType();
            commonInput.InputReference = "TADM1234567890";
            commonInput.Request = new RequestType();
            commonInput.Request.IsTest = true;
            commonInput.Origin = new OrigineType();
            commonInput.Origin.Package = new PackageType();
            commonInput.Origin.Package.Name = "eH-I Test";
            commonInput.Origin.Package.License = new LicenseType();
            commonInput.Origin.Package.License.Username = "******"; //provide you own license
            commonInput.Origin.Package.License.Password = "******"; //provide your own password
            commonInput.Origin.SiteID = "01"; //CareNet Gateway ID.
            commonInput.Origin.CareProvider = new CareProviderType();
            commonInput.Origin.CareProvider.Nihii = new NihiiType();
            commonInput.Origin.CareProvider.Nihii.Quality = "hospital";
            commonInput.Origin.CareProvider.Nihii.Value = "71022212000";
            commonInput.Origin.CareProvider.Organization = new IdType();
            commonInput.Origin.CareProvider.Organization.Nihii = commonInput.Origin.CareProvider.Nihii;

            //create blob value
            Stream raw = new MemoryStream(Encoding.ASCII.GetBytes(RandomString(1024*1024))); //you might use a file instead
            MemoryStream deflated = new MemoryStream();
            DeflateStream deflater = new DeflateStream(deflated, CompressionMode.Compress, true);
            raw.CopyTo(deflater);
            deflater.Flush();
            deflater.Close();

            //create blob
            Blob blob = new Blob();
            blob.MessageName = "ADM";
            blob.Id = "_" + Guid.NewGuid().ToString();
            blob.ContentType = "text/plain";
            blob.Value = deflated.ToArray();

            //Create Xml with the blob inside it to sign.
            XmlDocument signDoc;
            using(MemoryStream signDocStream = new MemoryStream()) {
                XmlWriter signDocWriter = XmlWriter.Create(signDocStream);
                signDocWriter.WriteStartElement("root");

                XmlSerializer serializer = new XmlSerializer(typeof(Blob), new XmlRootAttribute("Detail"));
                serializer.Serialize(signDocWriter, blob);

                signDocWriter.WriteEndElement();
                signDocWriter.Flush();

                signDocStream.Seek(0, SeekOrigin.Begin);
                signDoc = new XmlDocument();
                signDoc.PreserveWhitespace = true;
                signDoc.Load(signDocStream);
            }

            //create the xades-t
            var xigner = new XadesCreator(sign);
            xigner.TimestampProvider = new EHealthTimestampProvider(tsaClient);
            xigner.DataTransforms.Add(new XmlDsigBase64Transform());
            xigner.DataTransforms.Add(new OptionalDeflateTransform());
            XmlElement xades = xigner.CreateXadesT(signDoc, blob.Id);

            //conver the xades-t to byte array
            MemoryStream xadesSteam = new MemoryStream();
            using (var writer = XmlWriter.Create(xadesSteam))
            {
                xades.WriteTo(writer);
            }

            //Create the Base64 structure
            base64Binary xadesParam = new base64Binary();
            xadesParam.contentType = "text/xml";
            xadesParam.Value = xadesSteam.ToArray();

            //Send the message
            Thread.Sleep(1000); //sleep to let the eID recover :(
            TAck nipAck = client.post(commonInput, blob, xadesParam);

            //check if the messages was correctly send
            Assert.AreEqual("urn:nip:tack:result:major:success", nipAck.ResultMajor);

            //Get any waiting responses
            MsgQuery msgQuery = new MsgQuery();
            msgQuery.Max = 1; //best to specify to avoid quota exceeds or memory issues
            msgQuery.Include = true;
            Query tackQuery = new Query();
            tackQuery.Max = 10; //best to specify, but since they are smaller we can handle more
            tackQuery.Include = true;

            //Get the messages & tACK
            Thread.Sleep(1000); //sleep to let the eID recover :(
            Responses rsp = client.get(commonInput.Origin, msgQuery, tackQuery);

            //Collect the hash values of the messages & the tack
            //Should be a list of bytes arrays, but WCF isn't that smart so you need to do the encoding (base64, sperated by spaces)
            StringBuilder msgHashValues = new StringBuilder();
            if (rsp.MsgResponse != null)
            {
                foreach (MsgResponse msgRsp in rsp.MsgResponse)
                {
                    //Parse the xades, and rework it to a doc that contains the detail & xades.
                    XmlDocument verifyDoc;
                    using (MemoryStream verifyDocStream = new MemoryStream())
                    {
                        //Create new doc with element root
                        XmlWriter verifyDocWriter = XmlWriter.Create(verifyDocStream);
                        verifyDocWriter.WriteStartElement("root", "urn:dummy");

                        //Add blob (detail)
                        XmlSerializer serializer = new XmlSerializer(typeof(Blob), "urn:be:cin:types:v1");
                        serializer.Serialize(verifyDocWriter, msgRsp.Detail);

                        //Add xades-T
                        XmlDocument xadesDoc = new XmlDocument();
                        xadesDoc.PreserveWhitespace = true;
                        xadesDoc.Load(new MemoryStream(msgRsp.Xadest.Value));
                        xadesDoc.DocumentElement.WriteTo(verifyDocWriter);

                        verifyDocWriter.WriteEndElement();
                        verifyDocWriter.Flush();

                        //Reload the result
                        verifyDocStream.Seek(0, SeekOrigin.Begin);
                        verifyDoc = new XmlDocument();
                        verifyDoc.PreserveWhitespace = true;
                        verifyDoc.Load(verifyDocStream);

                        //Validate the doc
                        XmlElement prop = (XmlElement) XadesTools.FindXadesProperties(verifyDoc.DocumentElement)[0];
                        XadesVerifier verifier = new XadesVerifier();
                        verifier.RevocationMode = X509RevocationMode.NoCheck; //only for testing
                        verifier.TrustedTsaCerts.Add(tsaTrust);
                        SignatureInfo info = verifier.Verify(verifyDoc, prop);

                        //check info (time & certificate) to your own rules.
                    }

                    if (msgHashValues.Length != 0) msgHashValues.Append(" ");
                    msgHashValues.Append(Convert.ToBase64String(msgRsp.Detail.HashValue));
                }
            }
            List<String> resend = new List<string>();
            StringBuilder tackContents = new StringBuilder();
            if (rsp.TAckResponse != null)
            {
                foreach (TAckResponse tackRsp in rsp.TAckResponse)
                {
                    //Parse the xades, and rework it to a doc that contains the detail & xades.
                    XmlDocument verifyDoc;
                    using (MemoryStream verifyDocStream = new MemoryStream())
                    {
                        //Create new doc with element root
                        XmlWriter verifyDocWriter = XmlWriter.Create(verifyDocStream);
                        verifyDocWriter.WriteStartElement("root", "urn:dummy");

                        //Add blob (detail)
                        XmlSerializer serializer = new XmlSerializer(typeof(TAck), "urn:be:cin:nip:async:generic");
                        serializer.Serialize(verifyDocWriter, tackRsp.TAck);

                        //Add xades-T
                        XmlDocument xadesDoc = new XmlDocument();
                        xadesDoc.PreserveWhitespace = true;
                        xadesDoc.Load(new MemoryStream(tackRsp.Xadest.Value));
                        xadesDoc.DocumentElement.WriteTo(verifyDocWriter);

                        verifyDocWriter.WriteEndElement();
                        verifyDocWriter.Flush();

                        //Reload the result
                        verifyDocStream.Seek(0, SeekOrigin.Begin);
                        verifyDoc = new XmlDocument();
                        verifyDoc.PreserveWhitespace = true;
                        verifyDoc.Load(verifyDocStream);

                        //Validate the doc
                        XmlElement prop = (XmlElement)XadesTools.FindXadesProperties(verifyDoc.DocumentElement)[0];
                        XadesVerifier verifier = new XadesVerifier();
                        verifier.RevocationMode = X509RevocationMode.NoCheck; //only for testing
                        verifier.TrustedTsaCerts.Add(tsaTrust);
                        SignatureInfo info = verifier.Verify(verifyDoc, prop);

                        //check info (time & certificate) to your own rules.
                    }

                    //send failed, resend later.
                    if ("urn:nip:tack:result:major:success" != tackRsp.TAck.ResultMajor)
                    {
                        resend.Add(tackRsp.TAck.AppliesTo);
                    }

                    if (tackContents.Length != 0) tackContents.Append(" ");
                    tackContents.Append(Convert.ToBase64String(tackRsp.TAck.Value)); //the content of the tAck is already a hash...
                }
            }

            //Confirm the received messages & tack
            Thread.Sleep(1000); //sleep to let the eID recover :(
            client.confirm(commonInput.Origin, msgHashValues.ToString(), tackContents.ToString());

            //We should not have anything to resend
            Assert.AreEqual(0, resend.Count);
        }
Exemplo n.º 7
0
        private void DoTest(GenericAsyncClient client, TimeStampAuthorityClient tsaClient)
        {
            //Create common input with info about the requestor, must match SAML
            CommonInputType commonInput = new CommonInputType();

            commonInput.InputReference                         = "TADM1234567890";
            commonInput.Request                                = new RequestType();
            commonInput.Request.IsTest                         = true;
            commonInput.Origin                                 = new OrigineType();
            commonInput.Origin.Package                         = new PackageType();
            commonInput.Origin.Package.Name                    = "eH-I Test";
            commonInput.Origin.Package.License                 = new LicenseType();
            commonInput.Origin.Package.License.Username        = "******";      //provide you own license
            commonInput.Origin.Package.License.Password        = "******"; //provide your own password
            commonInput.Origin.SiteID                          = "01";       //CareNet Gateway ID.
            commonInput.Origin.CareProvider                    = new CareProviderType();
            commonInput.Origin.CareProvider.Nihii              = new NihiiType();
            commonInput.Origin.CareProvider.Nihii.Quality      = "hospital";
            commonInput.Origin.CareProvider.Nihii.Value        = "71022212000";
            commonInput.Origin.CareProvider.Organization       = new IdType();
            commonInput.Origin.CareProvider.Organization.Nihii = commonInput.Origin.CareProvider.Nihii;

            //create blob value
            Stream        raw      = new MemoryStream(Encoding.ASCII.GetBytes(RandomString(1024 * 1024))); //you might use a file instead
            MemoryStream  deflated = new MemoryStream();
            DeflateStream deflater = new DeflateStream(deflated, CompressionMode.Compress, true);

            raw.CopyTo(deflater);
            deflater.Flush();
            deflater.Close();

            //create blob
            Blob blob = new Blob();

            blob.MessageName = "ADM";
            blob.Id          = "_" + Guid.NewGuid().ToString();
            blob.ContentType = "text/plain";
            blob.Value       = deflated.ToArray();

            //Create Xml with the blob inside it to sign.
            XmlDocument signDoc;

            using (MemoryStream signDocStream = new MemoryStream()) {
                XmlWriter signDocWriter = XmlWriter.Create(signDocStream);
                signDocWriter.WriteStartElement("root");

                XmlSerializer serializer = new XmlSerializer(typeof(Blob), new XmlRootAttribute("Detail"));
                serializer.Serialize(signDocWriter, blob);

                signDocWriter.WriteEndElement();
                signDocWriter.Flush();

                signDocStream.Seek(0, SeekOrigin.Begin);
                signDoc = new XmlDocument();
                signDoc.PreserveWhitespace = true;
                signDoc.Load(signDocStream);
            }

            //create the xades-t
            var xigner = new XadesCreator(sign);

            xigner.TimestampProvider = new EHealthTimestampProvider(tsaClient);
            xigner.DataTransforms.Add(new XmlDsigBase64Transform());
            xigner.DataTransforms.Add(new OptionalDeflateTransform());
            XmlElement xades = xigner.CreateXadesT(signDoc, blob.Id);

            //conver the xades-t to byte array
            MemoryStream xadesSteam = new MemoryStream();

            using (var writer = XmlWriter.Create(xadesSteam))
            {
                xades.WriteTo(writer);
            }

            //Create the Base64 structure
            base64Binary xadesParam = new base64Binary();

            xadesParam.contentType = "text/xml";
            xadesParam.Value       = xadesSteam.ToArray();

            //Send the message
            Thread.Sleep(1000); //sleep to let the eID recover :(
            TAck nipAck = client.post(commonInput, blob, xadesParam);

            //check if the messages was correctly send
            Assert.AreEqual("urn:nip:tack:result:major:success", nipAck.ResultMajor);

            //Get any waiting responses
            MsgQuery msgQuery = new MsgQuery();

            msgQuery.Max     = 1; //best to specify to avoid quota exceeds or memory issues
            msgQuery.Include = true;
            Query tackQuery = new Query();

            tackQuery.Max     = 10; //best to specify, but since they are smaller we can handle more
            tackQuery.Include = true;

            //Get the messages & tACK
            Thread.Sleep(1000); //sleep to let the eID recover :(
            Responses rsp = client.get(commonInput.Origin, msgQuery, tackQuery);

            //Collect the hash values of the messages & the tack
            //Should be a list of bytes arrays, but WCF isn't that smart so you need to do the encoding (base64, sperated by spaces)
            StringBuilder msgHashValues = new StringBuilder();

            if (rsp.MsgResponse != null)
            {
                foreach (MsgResponse msgRsp in rsp.MsgResponse)
                {
                    //Parse the xades, and rework it to a doc that contains the detail & xades.
                    XmlDocument verifyDoc;
                    using (MemoryStream verifyDocStream = new MemoryStream())
                    {
                        //Create new doc with element root
                        XmlWriter verifyDocWriter = XmlWriter.Create(verifyDocStream);
                        verifyDocWriter.WriteStartElement("root", "urn:dummy");

                        //Add blob (detail)
                        XmlSerializer serializer = new XmlSerializer(typeof(Blob), "urn:be:cin:types:v1");
                        serializer.Serialize(verifyDocWriter, msgRsp.Detail);

                        //Add xades-T
                        XmlDocument xadesDoc = new XmlDocument();
                        xadesDoc.PreserveWhitespace = true;
                        xadesDoc.Load(new MemoryStream(msgRsp.Xadest.Value));
                        xadesDoc.DocumentElement.WriteTo(verifyDocWriter);

                        verifyDocWriter.WriteEndElement();
                        verifyDocWriter.Flush();

                        //Reload the result
                        verifyDocStream.Seek(0, SeekOrigin.Begin);
                        verifyDoc = new XmlDocument();
                        verifyDoc.PreserveWhitespace = true;
                        verifyDoc.Load(verifyDocStream);

                        //Validate the doc
                        XmlElement    prop     = (XmlElement)XadesTools.FindXadesProperties(verifyDoc.DocumentElement)[0];
                        XadesVerifier verifier = new XadesVerifier();
                        verifier.RevocationMode = X509RevocationMode.NoCheck; //only for testing
                        verifier.TrustedTsaCerts.Add(tsaTrust);
                        SignatureInfo info = verifier.Verify(verifyDoc, prop);

                        //check info (time & certificate) to your own rules.
                    }

                    if (msgHashValues.Length != 0)
                    {
                        msgHashValues.Append(" ");
                    }
                    msgHashValues.Append(Convert.ToBase64String(msgRsp.Detail.HashValue));
                }
            }
            List <String> resend       = new List <string>();
            StringBuilder tackContents = new StringBuilder();

            if (rsp.TAckResponse != null)
            {
                foreach (TAckResponse tackRsp in rsp.TAckResponse)
                {
                    //Parse the xades, and rework it to a doc that contains the detail & xades.
                    XmlDocument verifyDoc;
                    using (MemoryStream verifyDocStream = new MemoryStream())
                    {
                        //Create new doc with element root
                        XmlWriter verifyDocWriter = XmlWriter.Create(verifyDocStream);
                        verifyDocWriter.WriteStartElement("root", "urn:dummy");

                        //Add blob (detail)
                        XmlSerializer serializer = new XmlSerializer(typeof(TAck), "urn:be:cin:nip:async:generic");
                        serializer.Serialize(verifyDocWriter, tackRsp.TAck);

                        //Add xades-T
                        XmlDocument xadesDoc = new XmlDocument();
                        xadesDoc.PreserveWhitespace = true;
                        xadesDoc.Load(new MemoryStream(tackRsp.Xadest.Value));
                        xadesDoc.DocumentElement.WriteTo(verifyDocWriter);

                        verifyDocWriter.WriteEndElement();
                        verifyDocWriter.Flush();

                        //Reload the result
                        verifyDocStream.Seek(0, SeekOrigin.Begin);
                        verifyDoc = new XmlDocument();
                        verifyDoc.PreserveWhitespace = true;
                        verifyDoc.Load(verifyDocStream);

                        //Validate the doc
                        XmlElement    prop     = (XmlElement)XadesTools.FindXadesProperties(verifyDoc.DocumentElement)[0];
                        XadesVerifier verifier = new XadesVerifier();
                        verifier.RevocationMode = X509RevocationMode.NoCheck; //only for testing
                        verifier.TrustedTsaCerts.Add(tsaTrust);
                        SignatureInfo info = verifier.Verify(verifyDoc, prop);

                        //check info (time & certificate) to your own rules.
                    }

                    //send failed, resend later.
                    if ("urn:nip:tack:result:major:success" != tackRsp.TAck.ResultMajor)
                    {
                        resend.Add(tackRsp.TAck.AppliesTo);
                    }

                    if (tackContents.Length != 0)
                    {
                        tackContents.Append(" ");
                    }
                    tackContents.Append(Convert.ToBase64String(tackRsp.TAck.Value)); //the content of the tAck is already a hash...
                }
            }

            //Confirm the received messages & tack
            Thread.Sleep(1000); //sleep to let the eID recover :(
            client.confirm(commonInput.Origin, msgHashValues.ToString(), tackContents.ToString());

            //We should not have anything to resend
            Assert.AreEqual(0, resend.Count);
        }