コード例 #1
0
ファイル: DataObjectTest.cs プロジェクト: nlhepler/mono
		public void NewDataObject () 
		{
			string test = "<Test>DataObject</Test>";
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (test);

			DataObject obj1 = new DataObject ();
			Assert.IsTrue ((obj1.Data.Count == 0), "Data.Count==0");
			Assert.AreEqual ("<Object xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", (obj1.GetXml ().OuterXml), "Just constructed");

			obj1.Id = "id";
			obj1.MimeType = "mime";
			obj1.Encoding = "encoding";
			Assert.AreEqual ("<Object Id=\"id\" MimeType=\"mime\" Encoding=\"encoding\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\" />", (obj1.GetXml ().OuterXml), "Only attributes");

			obj1.Data = doc.ChildNodes;
			Assert.IsTrue ((obj1.Data.Count == 1), "Data.Count==1");

			XmlElement xel = obj1.GetXml ();

			DataObject obj2 = new DataObject ();
			obj2.LoadXml (xel);
			Assert.AreEqual ((obj1.GetXml ().OuterXml), (obj2.GetXml ().OuterXml), "obj1==obj2");

			DataObject obj3 = new DataObject (obj1.Id, obj1.MimeType, obj1.Encoding, doc.DocumentElement);
			Assert.AreEqual ((obj2.GetXml ().OuterXml), (obj3.GetXml ().OuterXml), "obj2==obj3");
		}
コード例 #2
0
        /// <summary>
        /// Method that return the Object for fixing validation problem
        /// </summary>
        /// <param name="SignatureID">ID of Signature</param>
        /// <param name="ManifestHashAlgorithm">Hash Algorithm</param>
        /// <returns>DataObject</returns>
        private System.Security.Cryptography.Xml.DataObject CreateOfficeObject(string SignatureID, string ManifestHashAlgorithm)
        {
            XmlDocument document = new XmlDocument();

            document.LoadXml(String.Format(officeDocument, SignatureID, ManifestHashAlgorithm));
            System.Security.Cryptography.Xml.DataObject officeObject = new System.Security.Cryptography.Xml.DataObject();
            // do not change the order of the following two lines
            officeObject.LoadXml(document.DocumentElement); // resets ID
            officeObject.Id = OfficeObjectID;               // required ID, do not change
            return(officeObject);
        }
コード例 #3
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            if ((value.LocalName == XmlSignature.ElementNames.Signature) && (value.NamespaceURI == XmlSignature.NamespaceURI))
            {
                id = GetAttribute(value, XmlSignature.AttributeNames.Id);

                // LAMESPEC: This library is totally useless against eXtensibly Marked-up document.
                int        i     = NextElementPos(value.ChildNodes, 0, XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI, true);
                XmlElement sinfo = (XmlElement)value.ChildNodes [i];
                info = new SignedInfo();
                info.LoadXml(sinfo);

                i = NextElementPos(value.ChildNodes, ++i, XmlSignature.ElementNames.SignatureValue, XmlSignature.NamespaceURI, true);
                XmlElement sigValue = (XmlElement)value.ChildNodes [i];
                signature = Convert.FromBase64String(sigValue.InnerText);

                // signature isn't required: <element ref="ds:KeyInfo" minOccurs="0"/>
                i = NextElementPos(value.ChildNodes, ++i, XmlSignature.ElementNames.KeyInfo, XmlSignature.NamespaceURI, false);
                if (i > 0)
                {
                    XmlElement kinfo = (XmlElement)value.ChildNodes [i];
                    key = new KeyInfo();
                    key.LoadXml(kinfo);
                }

                XmlNodeList xnl = value.SelectNodes("xd:Object", dsigNsmgr);
                foreach (XmlElement xn in xnl)
                {
                    DataObject obj = new DataObject();
                    obj.LoadXml(xn);
                    AddObject(obj);
                }
            }
            else
            {
                throw new CryptographicException("Malformed element: Signature.");
            }

            // if invalid
            if (info == null)
            {
                throw new CryptographicException("SignedInfo");
            }
            if (signature == null)
            {
                throw new CryptographicException("SignatureValue");
            }
        }
コード例 #4
0
ファイル: DataObjectTest.cs プロジェクト: nlhepler/mono
		public void ImportDataObject () 
		{
			string value1 = "<Object Id=\"id\" MimeType=\"mime\" Encoding=\"encoding\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\">DataObject1</Test><Test xmlns=\"\">DataObject2</Test></Object>";
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (value1);

			DataObject obj1 = new DataObject ();
			obj1.LoadXml (doc.DocumentElement);
			Assert.IsTrue ((obj1.Data.Count == 2), "Data.Count==2");

			string s = (obj1.GetXml ().OuterXml);
			Assert.AreEqual (value1, s, "DataObject 1");

			string value2 = "<Object xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\" /></Object>";
			doc = new XmlDocument ();
			doc.LoadXml (value2);

			DataObject obj2 = new DataObject ();
			obj2.LoadXml (doc.DocumentElement);

			s = (obj2.GetXml ().OuterXml);
			Assert.AreEqual (value2, s, "DataObject 2");

			string value3 = "<Object Id=\"id\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\" /></Object>";
			doc = new XmlDocument ();
			doc.LoadXml (value3);

			DataObject obj3 = new DataObject ();
			obj3.LoadXml (doc.DocumentElement);

			s = (obj3.GetXml ().OuterXml);
			Assert.AreEqual (value3, s, "DataObject 3");

			string value4 = "<Object MimeType=\"mime\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\"><Test xmlns=\"\" /></Object>";
			doc = new XmlDocument ();
			doc.LoadXml (value4);

			DataObject obj4 = new DataObject ();
			obj4.LoadXml (doc.DocumentElement);

			s = (obj4.GetXml ().OuterXml);
			Assert.AreEqual (value4, s, "DataObject 4");
		}
コード例 #5
0
ファイル: DocumentSignature.cs プロジェクト: frexin/DocSign
        static System.Security.Cryptography.Xml.DataObject CreateOfficeObject(
            string signatureID, string manifestHashAlgorithm)
        {
            XmlDocument document = new XmlDocument();

            document.LoadXml(String.Format(
                                 "<OfficeObject>" +
                                 "<SignatureProperties xmlns=\"http://www.w3.org/2000/09/xmldsig#\">" +
                                 "<SignatureProperty Id=\"idOfficeV1Details\" Target=\"{0}\">" +
                                 "<SignatureInfoV1 xmlns=\"http://schemas.microsoft.com/office/2006/digsig\">" +
                                 "<SetupID></SetupID>" +
                                 "<ManifestHashAlgorithm>{1}</ManifestHashAlgorithm>" +
                                 "<SignatureProviderId>{2}</SignatureProviderId>" +
                                 "</SignatureInfoV1>" +
                                 "</SignatureProperty>" +
                                 "</SignatureProperties>" +
                                 "</OfficeObject>", signatureID, manifestHashAlgorithm, "{F5AC7D23-DA04-45F5-ABCB-38CE7A982553}"));
            System.Security.Cryptography.Xml.DataObject officeObject = new System.Security.Cryptography.Xml.DataObject();
            // do not change the order of the following two lines
            officeObject.LoadXml(document.DocumentElement); // resets ID
            officeObject.Id = OfficeObjectID;               // required ID, do not change
            return(officeObject);
        }
コード例 #6
0
        public void LoadXml(XmlElement value)
        {
            // Make sure we don't get passed null
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // Signature
            XmlElement signatureElement = value;

            if (!signatureElement.LocalName.Equals("Signature"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }

            // Attributes
            m_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl);
            if (!Utils.VerifyAttributes(signatureElement, "Id"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
            int expectedChildNodes = 0;

            // SignedInfo
            XmlNodeList signedInfoNodes = signatureElement.SelectNodes("ds:SignedInfo", nsm);

            if (signedInfoNodes == null || signedInfoNodes.Count == 0 || (!Utils.GetAllowAdditionalSignatureNodes() && signedInfoNodes.Count > 1))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
            }
            XmlElement signedInfoElement = signedInfoNodes[0] as XmlElement;

            expectedChildNodes += signedInfoNodes.Count;

            this.SignedInfo = new SignedInfo();
            this.SignedInfo.LoadXml(signedInfoElement);

            // SignatureValue
            XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm);

            if (signatureValueNodes == null || signatureValueNodes.Count == 0 || (!Utils.GetAllowAdditionalSignatureNodes() && signatureValueNodes.Count > 1))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignatureValue");
            }
            XmlElement signatureValueElement = signatureValueNodes[0] as XmlElement;

            expectedChildNodes += signatureValueNodes.Count;
            m_signatureValue    = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText));
            m_signatureValueId  = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl);
            if (!Utils.VerifyAttributes(signatureValueElement, "Id"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignatureValue");
            }

            // KeyInfo - optional single element
            XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm);

            m_keyInfo = new KeyInfo();
            if (keyInfoNodes != null)
            {
                if (!Utils.GetAllowAdditionalSignatureNodes() && keyInfoNodes.Count > 1)
                {
                    throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "KeyInfo");
                }
                foreach (XmlNode node in keyInfoNodes)
                {
                    XmlElement keyInfoElement = node as XmlElement;
                    if (keyInfoElement != null)
                    {
                        m_keyInfo.LoadXml(keyInfoElement);
                    }
                }
                expectedChildNodes += keyInfoNodes.Count;
            }

            // Object - zero or more elements allowed
            XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm);

            m_embeddedObjects.Clear();
            if (objectNodes != null)
            {
                foreach (XmlNode node in objectNodes)
                {
                    XmlElement objectElement = node as XmlElement;
                    if (objectElement != null)
                    {
                        DataObject dataObj = new DataObject();
                        dataObj.LoadXml(objectElement);
                        m_embeddedObjects.Add(dataObj);
                    }
                }
                expectedChildNodes += objectNodes.Count;
            }

            // Select all elements that have Id attributes
            XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm);

            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    m_referencedItems.Add(node);
                }
            }

            // Verify that there aren't any extra nodes that aren't allowed
            if (!Utils.GetAllowAdditionalSignatureNodes() && (signatureElement.SelectNodes("*").Count != expectedChildNodes))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }
        }
コード例 #7
0
ファイル: DataObjectTest.cs プロジェクト: nlhepler/mono
		public void PropertySetMakesDocumentDifferent ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<Object xmlns='http://www.w3.org/2000/09/xmldsig#'>test</Object>");
			DataObject obj = new DataObject ();
			XmlElement el1 = obj.GetXml ();
			obj.LoadXml (doc.DocumentElement);
			obj.Id = "hogehoge";
			XmlElement el2 = obj.GetXml ();
			Assert.IsTrue (doc != el2.OwnerDocument, "Document is not kept when properties are set");
		}
コード例 #8
0
ファイル: DataObjectTest.cs プロジェクト: nlhepler/mono
		public void EnvelopedObject ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<envelope><Object xmlns:dsig='http://www.w3.org/2000/09/xmldsig#' xmlns='http://www.w3.org/2000/09/xmldsig#'>test</Object></envelope>");
			DataObject obj = new DataObject ();
			obj.LoadXml (doc.DocumentElement.FirstChild as XmlElement);
			obj.Id = "hoge";
			obj.MimeType = "application/octet-stream";
			obj.Encoding = "euc-kr";
			XmlElement el1 = obj.GetXml ();
			Assert.AreEqual ("<Object Id=\"hoge\" MimeType=\"application/octet-stream\" Encoding=\"euc-kr\" xmlns=\"http://www.w3.org/2000/09/xmldsig#\">test</Object>", el1.OuterXml);
			/* looks curious? but the element does not look to 
			   be appended to the document.
			   Just commented out since it is not fixed.
			Assert.AreEqual (String.Empty, el1.OwnerDocument.OuterXml);
			*/
		}
コード例 #9
0
ファイル: DataObjectTest.cs プロジェクト: nlhepler/mono
		public void InvalidDataObject3 () 
		{
			DataObject obj1 = new DataObject ();
			// seems this isn't invalid !?!
			// but no exception is thrown
			string value = "<Test>Bad</Test>";
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (value);
			obj1.LoadXml (doc.DocumentElement);
			string s = (obj1.GetXml ().OuterXml);
			Assert.AreEqual (value, s, "DataObject Bad");
		}
コード例 #10
0
ファイル: DataObjectTest.cs プロジェクト: nlhepler/mono
		public void GetXmlKeepDocument ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<Object xmlns='http://www.w3.org/2000/09/xmldsig#'>test</Object>");
			DataObject obj = new DataObject ();
			XmlElement el1 = obj.GetXml ();
			obj.LoadXml (doc.DocumentElement);
//			obj.Id = "hogehoge";
			XmlElement el2 = obj.GetXml ();
			Assert.AreEqual (doc, el2.OwnerDocument, "Document is kept unless setting properties");
		}
コード例 #11
0
ファイル: Signature.cs プロジェクト: ash2005/z
        public void LoadXml(XmlElement value)
        {
            // Make sure we don't get passed null
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // Signature
            XmlElement signatureElement = value;

            if (!signatureElement.LocalName.Equals("Signature"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }

            // Id attribute -- optional
            m_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl);

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // SignedInfo
            XmlElement signedInfoElement = signatureElement.SelectSingleNode("ds:SignedInfo", nsm) as XmlElement;

            if (signedInfoElement == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
            }

            this.SignedInfo = new SignedInfo();
            this.SignedInfo.LoadXml(signedInfoElement);

            // SignatureValue
            XmlElement signatureValueElement = signatureElement.SelectSingleNode("ds:SignatureValue", nsm) as XmlElement;

            if (signatureValueElement == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureValue");
            }
            m_signatureValue   = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText));
            m_signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl);

            XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm);

            m_keyInfo = new KeyInfo();
            if (keyInfoNodes != null)
            {
                foreach (XmlNode node in keyInfoNodes)
                {
                    XmlElement keyInfoElement = node as XmlElement;
                    if (keyInfoElement != null)
                    {
                        m_keyInfo.LoadXml(keyInfoElement);
                    }
                }
            }

            XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm);

            m_embeddedObjects.Clear();
            if (objectNodes != null)
            {
                foreach (XmlNode node in objectNodes)
                {
                    XmlElement objectElement = node as XmlElement;
                    if (objectElement != null)
                    {
                        DataObject dataObj = new DataObject();
                        dataObj.LoadXml(objectElement);
                        m_embeddedObjects.Add(dataObj);
                    }
                }
            }

            // Select all elements that have Id attributes
            XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm);

            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    m_referencedItems.Add(node);
                }
            }
        }
コード例 #12
0
ファイル: DataObjectTest.cs プロジェクト: nlhepler/mono
		public void InvalidDataObject2 () 
		{
			DataObject obj1 = new DataObject ();
			obj1.LoadXml (null);
		}
コード例 #13
0
ファイル: Utils.cs プロジェクト: isdoc/dsig-demo
    // Třída podepíše certifikátem dokument XML a přidá časové razítko
    // Pokud je již dokument podepsaný, přidá se další podpis
    public XmlDocument SignWithTimestamp(XmlDocument doc, X509Certificate2 cert, string tsURL, string tsUsername, string tsPassword)
    {
        // před podepisováním z dokumentu odstraníme komentáře (.NET s nimi má problémy pokud se kombinují s XPath transformacemi)
        XmlDocument strippedDoc = RemoveComments(doc);

        // definice mapování prefixů na jmenné prostory
        XmlNamespaceManager manager = new XmlNamespaceManager(strippedDoc.NameTable);
        manager.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");

        // zjištění kolik podpisů již v dokumentu je
        int signatures = strippedDoc.SelectNodes("//dsig:Signature", manager).Count;

        string signatureID = (signatures + 1).ToString();

        // vytvoření elementu Object pro časové razítko
        XmlElement objectElement = doc.CreateElement("Object", "http://www.w3.org/2000/09/xmldsig#");

        // spočítání otisku certifikátu
        SHA256 sha256 = new SHA256Managed();
        string certHash = Convert.ToBase64String(sha256.ComputeHash(cert.GetRawCertData()));

        objectElement.InnerXml = @"<xades:QualifyingProperties xmlns:xades='http://uri.etsi.org/01903/v1.3.2#' Target='#Signature-" + signatureID + @"' xmlns='http://www.w3.org/2000/09/xmldsig#'>
                <xades:SignedProperties Id='Signature-" + signatureID + @"-SignedProperties'>
                  <xades:SignedSignatureProperties>
                    <xades:SigningTime>" + XmlConvert.ToString(DateTime.Now.ToUniversalTime(), XmlDateTimeSerializationMode.RoundtripKind) + @"</xades:SigningTime>
                    <xades:SigningCertificate>
                      <xades:Cert>
                        <xades:CertDigest>
                          <DigestMethod Algorithm='http://www.w3.org/2001/04/xmlenc#sha256'></DigestMethod>
                          <DigestValue>" + certHash + @"</DigestValue>
                        </xades:CertDigest>
                        <xades:IssuerSerial>
                          <X509IssuerName>" + cert.IssuerName + @"</X509IssuerName>
                          <X509SerialNumber>" + cert.GetSerialNumberString() + @"</X509SerialNumber>
                        </xades:IssuerSerial>
                      </xades:Cert>
                    </xades:SigningCertificate>
                  </xades:SignedSignatureProperties>
                  <xades:SignedDataObjectProperties>
                    <xades:DataObjectFormat ObjectReference='#Signature-" + signatureID + @"-Document-Reference'>
                      <xades:MimeType>application/xml</xades:MimeType>
                    </xades:DataObjectFormat>
                  </xades:SignedDataObjectProperties>
                </xades:SignedProperties>
                <xades:UnsignedProperties>
                  <xades:UnsignedSignatureProperties>
                    <xades:SignatureTimeStamp>
                      <xades:EncapsulatedTimeStamp Encoding='http://uri.etsi.org/01903/v1.2.2#DER'></xades:EncapsulatedTimeStamp>
                    </xades:SignatureTimeStamp>
                  </xades:UnsignedSignatureProperties>
                </xades:UnsignedProperties>
               </xades:QualifyingProperties>";


        // objekt sloužící pro vytvoření podpisu
        CustomIdSignedXml signedXml = new CustomIdSignedXml(strippedDoc, objectElement);

        // podepisovat budeme privátním klíčem z certifikátu
        signedXml.SigningKey = cert.PrivateKey;

        // podepisovat budeme pomocí RSA-SHA256
        signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";

        // reference na podepisovaný dokument ("" znamená celý dokument)
        Reference reference = new Reference();
        reference.Uri = "";
        reference.Id = "Signature-" + signatureID + "-Document-Reference";

        // pro výpočet otisku se bude používat SHA-256
        reference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        // digitální podpis bude přímo součástí dokumentu XML (tzv. "enveloped signature")
        XmlDsigEnvelopedSignatureTransform envTransform = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(envTransform);

        // navíc budeme používat XPath transoformaci, která dovoluje přidat několik podpisů najednou
        XmlDsigXPathTransform xpathTransform = new XmlDsigXPathTransform();

        // příprava definice XPath transformace jako struktura XML signature
        XmlDocument transformBody = new XmlDocument();

        // podoba XPath filtru se liší podle počtu podpisů
        if (signatures == 0)
            transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature)</dsig:XPath>");
        else
            transformBody.LoadXml("<dsig:XPath xmlns:dsig='http://www.w3.org/2000/09/xmldsig#'>not(ancestor-or-self::dsig:Signature) or not(ancestor-or-self::dsig:Signature/preceding-sibling::dsig:Signature[" + signatures + "])</dsig:XPath>");

        // načtení definice XPath transformace do objektu
        xpathTransform.LoadInnerXml(transformBody.SelectNodes("/*[1]"));

        // přidání XPath transformace
        reference.AddTransform(xpathTransform);

        // přidání reference do podpisu
        signedXml.AddReference(reference);

        // reference na SignedProperties -- XAdES-BES vyžaduje podpis certifikátu
        Reference spReference = new Reference();
        spReference.Uri = "#Signature-" + signatureID + "-SignedProperties";

        // pro výpočet otisku se bude používat SHA-256
        spReference.DigestMethod = "http://www.w3.org/2001/04/xmlenc#sha256";

        // přidání reference do podpisu
        signedXml.AddReference(spReference);

        // přidání certifikátu do podpisu
        KeyInfo keyInfo = new KeyInfo();
        keyInfo.AddClause(new KeyInfoX509Data(cert));
        signedXml.KeyInfo = keyInfo;

        // přidání objektu s časovým razítkem do podpisu
        DataObject dataObj = new DataObject();
        dataObj.LoadXml(objectElement);
        signedXml.AddObject(dataObj);

        // výpočet podpisu
        signedXml.ComputeSignature();

        // získání XML reprezentace podpisu
        XmlElement xmlSignature = signedXml.GetXml();

        // k podpisu přidáme identifikátor, tak jak doporučuje standard ISDOC
        xmlSignature.SetAttribute("Id", "Signature-" + signatureID);

        // XML dokument pro podepsaný výsledek
        XmlDocument result = new XmlDocument();

        // bílé znaky musíme zachovat, jinak se špatně spočte hash
        result.PreserveWhitespace = true;

        // načtení původního dokumentu
        result.AppendChild(result.ImportNode(strippedDoc.DocumentElement, true));

        // připojení podpisu na konec dokumentu XML
        result.DocumentElement.AppendChild(result.ImportNode(xmlSignature, true));

        // Spočítání otisku digitálního podpisu
        byte[] digest;
        digest = sha256.ComputeHash(signedXml.SignatureValue);

        // generátor požadavků na časové razítko
        TimeStampRequestGenerator reqGen = new TimeStampRequestGenerator();

        // vytvoření dat pro požadavek na timestamp server
        TimeStampRequest request = reqGen.Generate(TspAlgorithms.Sha256, digest);

        // získání surových dat pro poslání na timestamp server
        byte[] reqData = request.GetEncoded();

        // inicializace požadavku na timestamp server
        HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(tsURL);
        httpReq.Method = "POST";
        httpReq.ContentType = "application/timestamp-query";
        httpReq.ContentLength = reqData.Length;
        httpReq.Credentials = new NetworkCredential(tsUsername, tsPassword);

        // odeslání požadavku na timestamp server
        Stream reqStream = httpReq.GetRequestStream();
        reqStream.Write(reqData, 0, reqData.Length);
        reqStream.Close();

        // přečtení odpovědi
        HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
        Stream respStream = new BufferedStream(httpResp.GetResponseStream());
        TimeStampResponse response = new TimeStampResponse(respStream);
        respStream.Close();
        
        // Console.WriteLine("Status razítkování: " + response.Status);
        // Console.WriteLine("Čas razítka: " + response.TimeStampToken.TimeStampInfo.GenTime.ToLocalTime());
        string timestamp = Convert.ToBase64String(response.GetEncoded());

        // doplnění získaného časového razítka do dokumentu
        XmlNamespaceManager nsmng = new XmlNamespaceManager(result.NameTable);
        nsmng.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
        nsmng.AddNamespace("xades", "http://uri.etsi.org/01903/v1.3.2#");
        XmlElement etsElement = (XmlElement)result.SelectSingleNode("//*[@Id = 'Signature-" + signatureID +"']/ds:Object/xades:QualifyingProperties/xades:UnsignedProperties/xades:UnsignedSignatureProperties/xades:SignatureTimeStamp/xades:EncapsulatedTimeStamp", nsmng);
        etsElement.InnerText = timestamp;

        return result;
    }
コード例 #14
0
        public void LoadXml(XmlElement value) {
             // Make sure we don't get passed null
            if (value == null)
                throw new ArgumentNullException("value");

            // Signature
            XmlElement signatureElement = value;
            if (!signatureElement.LocalName.Equals("Signature"))
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");

            // Id attribute -- optional
            m_id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl);

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);
            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // SignedInfo
            XmlElement signedInfoElement = signatureElement.SelectSingleNode("ds:SignedInfo", nsm) as XmlElement;
            if (signedInfoElement == null)
              throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"),"SignedInfo");

            this.SignedInfo = new SignedInfo();
            this.SignedInfo.LoadXml(signedInfoElement);

            // SignatureValue
            XmlElement signatureValueElement = signatureElement.SelectSingleNode("ds:SignatureValue", nsm) as XmlElement;
            if (signatureValueElement == null)
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"),"SignedInfo/SignatureValue");
            m_signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText));
            m_signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl);

            XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm);
            m_keyInfo = new KeyInfo();
            if (keyInfoNodes != null) {
                foreach(XmlNode node in keyInfoNodes) {
                    XmlElement keyInfoElement = node as XmlElement;
                    if (keyInfoElement != null)
                        m_keyInfo.LoadXml(keyInfoElement);
                }
            }

            XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm);
            m_embeddedObjects.Clear();
            if (objectNodes != null) {
                foreach(XmlNode node in objectNodes) {
                    XmlElement objectElement = node as XmlElement;
                    if (objectElement != null) {
                        DataObject dataObj = new DataObject();
                        dataObj.LoadXml(objectElement);
                        m_embeddedObjects.Add(dataObj);
                    }
                }
            }

            // Select all elements that have Id attributes
            XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm);
            if (nodeList != null) {
                foreach (XmlNode node in nodeList) {
                    m_referencedItems.Add(node);
                }
            }
        }
コード例 #15
0
        /// <include file='doc\Signature.uex' path='docs/doc[@for="Signature.LoadXml"]/*' />
        public void LoadXml(XmlElement value)
        {
            // Make sure we don't get passed null
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            // Signature
            XmlElement signatureElement = value;

            if (!signatureElement.LocalName.Equals("Signature"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }

            XmlAttributeCollection signatureAttributes = signatureElement.Attributes;
            XmlNode idAttribute = signatureAttributes["Id"];

            if (idAttribute == null)
            {
                m_strId = null;
            }
            //throw new CryptographicException(String.Format(Environment.GetResourceString("Cryptography_XML_MalformedXML"),"Signature"));

            // Look for SignedInfo and SignatureValue. There may optionally be
            // a KeyInfo and some Objects

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            // SignedInfo
            //XmlNodeList signatureChilds = signatureElement.GetElementsByTagName("SignedInfo", SignedXml.XmlDsigNamespaceUrl);
            XmlNodeList signatureChilds = signatureElement.SelectNodes("ds:SignedInfo", nsm);

            if (signatureChilds.Count == 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
            }
            XmlElement signedInfoElement = (XmlElement)signatureChilds.Item(0);

            m_signedInfo = new SignedInfo();
            m_signedInfo.LoadXml(signedInfoElement);

            // SignatureValue
            XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm);

            if (signatureValueNodes.Count == 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureValue");
            }
            XmlElement signatureValueElement = (XmlElement)signatureValueNodes.Item(0);

            m_rgbSignatureValue = Convert.FromBase64String(SignedXml.DiscardWhiteSpaces(signatureValueElement.InnerText));

            XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm);

            if (keyInfoNodes.Count != 0)
            {
                XmlElement keyInfoElement = (XmlElement)keyInfoNodes.Item(0);
                m_keyInfo = new KeyInfo();
                m_keyInfo.LoadXml(keyInfoElement);
            }

            XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm);

            for (int i = 0; i < objectNodes.Count; ++i)
            {
                XmlElement objectElement = (XmlElement)objectNodes.Item(i);
                DataObject dataObj       = new DataObject();
                dataObj.LoadXml(objectElement);
                m_embeddedObjects.Add(dataObj);
            }

            // Select all elements that have Id attributes
            XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm);

            if (nodeList != null)
            {
                foreach (XmlNode node in nodeList)
                {
                    m_referencedItems.Add(node);
                }
            }
        }
コード例 #16
0
 public void LoadXml(XmlElement value)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     XmlElement element = value;
     if (!element.LocalName.Equals("Signature"))
     {
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
     }
     this.m_id = System.Security.Cryptography.Xml.Utils.GetAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#");
     XmlNamespaceManager nsmgr = new XmlNamespaceManager(value.OwnerDocument.NameTable);
     nsmgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
     XmlElement element2 = element.SelectSingleNode("ds:SignedInfo", nsmgr) as XmlElement;
     if (element2 == null)
     {
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
     }
     this.SignedInfo = new System.Security.Cryptography.Xml.SignedInfo();
     this.SignedInfo.LoadXml(element2);
     XmlElement element3 = element.SelectSingleNode("ds:SignatureValue", nsmgr) as XmlElement;
     if (element3 == null)
     {
         throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureValue");
     }
     this.m_signatureValue = Convert.FromBase64String(System.Security.Cryptography.Xml.Utils.DiscardWhiteSpaces(element3.InnerText));
     this.m_signatureValueId = System.Security.Cryptography.Xml.Utils.GetAttribute(element3, "Id", "http://www.w3.org/2000/09/xmldsig#");
     XmlNodeList list = element.SelectNodes("ds:KeyInfo", nsmgr);
     this.m_keyInfo = new System.Security.Cryptography.Xml.KeyInfo();
     if (list != null)
     {
         foreach (XmlNode node in list)
         {
             XmlElement element4 = node as XmlElement;
             if (element4 != null)
             {
                 this.m_keyInfo.LoadXml(element4);
             }
         }
     }
     XmlNodeList list2 = element.SelectNodes("ds:Object", nsmgr);
     this.m_embeddedObjects.Clear();
     if (list2 != null)
     {
         foreach (XmlNode node2 in list2)
         {
             XmlElement element5 = node2 as XmlElement;
             if (element5 != null)
             {
                 DataObject obj2 = new DataObject();
                 obj2.LoadXml(element5);
                 this.m_embeddedObjects.Add(obj2);
             }
         }
     }
     XmlNodeList list3 = element.SelectNodes("//*[@Id]", nsmgr);
     if (list3 != null)
     {
         foreach (XmlNode node3 in list3)
         {
             this.m_referencedItems.Add(node3);
         }
     }
 }
コード例 #17
0
        public void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }
            XmlElement element = value;

            if (!element.LocalName.Equals("Signature"))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "Signature");
            }
            this.m_id = System.Security.Cryptography.Xml.Utils.GetAttribute(element, "Id", "http://www.w3.org/2000/09/xmldsig#");
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsmgr.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
            XmlElement element2 = element.SelectSingleNode("ds:SignedInfo", nsmgr) as XmlElement;

            if (element2 == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo");
            }
            this.SignedInfo = new System.Security.Cryptography.Xml.SignedInfo();
            this.SignedInfo.LoadXml(element2);
            XmlElement element3 = element.SelectSingleNode("ds:SignatureValue", nsmgr) as XmlElement;

            if (element3 == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidElement"), "SignedInfo/SignatureValue");
            }
            this.m_signatureValue   = Convert.FromBase64String(System.Security.Cryptography.Xml.Utils.DiscardWhiteSpaces(element3.InnerText));
            this.m_signatureValueId = System.Security.Cryptography.Xml.Utils.GetAttribute(element3, "Id", "http://www.w3.org/2000/09/xmldsig#");
            XmlNodeList list = element.SelectNodes("ds:KeyInfo", nsmgr);

            this.m_keyInfo = new System.Security.Cryptography.Xml.KeyInfo();
            if (list != null)
            {
                foreach (XmlNode node in list)
                {
                    XmlElement element4 = node as XmlElement;
                    if (element4 != null)
                    {
                        this.m_keyInfo.LoadXml(element4);
                    }
                }
            }
            XmlNodeList list2 = element.SelectNodes("ds:Object", nsmgr);

            this.m_embeddedObjects.Clear();
            if (list2 != null)
            {
                foreach (XmlNode node2 in list2)
                {
                    XmlElement element5 = node2 as XmlElement;
                    if (element5 != null)
                    {
                        DataObject obj2 = new DataObject();
                        obj2.LoadXml(element5);
                        this.m_embeddedObjects.Add(obj2);
                    }
                }
            }
            XmlNodeList list3 = element.SelectNodes("//*[@Id]", nsmgr);

            if (list3 != null)
            {
                foreach (XmlNode node3 in list3)
                {
                    this.m_referencedItems.Add(node3);
                }
            }
        }
コード例 #18
0
 private static DataObject CreateOfficeObject(string signatureID, string manifestHashAlgorithm)
 {
     var document = new XmlDocument();
     document.LoadXml(String.Format(Properties.Resources.OfficeObject, signatureID, manifestHashAlgorithm));
     var officeObject = new DataObject();
     // do not change the order of the following two lines
     officeObject.LoadXml(document.DocumentElement); // resets ID
     officeObject.Id = OfficeObjectID; // required ID, do not change
     return officeObject;
 }
コード例 #19
0
ファイル: Signature.cs プロジェクト: Xipas/Symplified.Auth
		public void LoadXml (XmlElement value) 
		{
			if (value == null)
				throw new ArgumentNullException ("value");

			if ((value.LocalName == XmlSignature.ElementNames.Signature) && (value.NamespaceURI == XmlSignature.NamespaceURI)) {
				id = GetAttribute (value, XmlSignature.AttributeNames.Id);

				// LAMESPEC: This library is totally useless against eXtensibly Marked-up document.
				int i = NextElementPos (value.ChildNodes, 0, XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI, true);
				XmlElement sinfo = (XmlElement) value.ChildNodes [i];
				info = new SignedInfo ();
				info.LoadXml (sinfo);

				i = NextElementPos (value.ChildNodes, ++i, XmlSignature.ElementNames.SignatureValue, XmlSignature.NamespaceURI, true);
				XmlElement sigValue = (XmlElement) value.ChildNodes [i];
				signature = Convert.FromBase64String (sigValue.InnerText);

				// signature isn't required: <element ref="ds:KeyInfo" minOccurs="0"/> 
				i = NextElementPos (value.ChildNodes, ++i, XmlSignature.ElementNames.KeyInfo, XmlSignature.NamespaceURI, false);
				if (i > 0) {
					XmlElement kinfo = (XmlElement) value.ChildNodes [i];
					key = new KeyInfo ();
					key.LoadXml (kinfo);
				}

				XmlNodeList xnl = value.SelectNodes ("xd:Object", dsigNsmgr);
				foreach (XmlElement xn in xnl) {
					DataObject obj = new DataObject ();
					obj.LoadXml (xn);
					AddObject (obj);
				}
			}
			else
				throw new CryptographicException ("Malformed element: Signature.");

			// if invalid
			if (info == null)
				throw new CryptographicException ("SignedInfo");
			if (signature == null)
				throw new CryptographicException ("SignatureValue");
		}