当前位置: 首页>>代码示例>>C#>>正文


C# Xml.SignedXml类代码示例

本文整理汇总了C#中System.Security.Cryptography.Xml.SignedXml的典型用法代码示例。如果您正苦于以下问题:C# SignedXml类的具体用法?C# SignedXml怎么用?C# SignedXml使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


SignedXml类属于System.Security.Cryptography.Xml命名空间,在下文中一共展示了SignedXml类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: EncodeCMS

        public override object EncodeCMS(X509Certificate2 certificate, string xmlFilePath)
        {
            XmlDocument Document = new XmlDocument();
            Document.PreserveWhitespace = true;
            XmlTextReader XmlFile = new XmlTextReader(xmlFilePath);
            Document.Load(XmlFile);
            XmlFile.Close();
            XmlNodeList SignaturesList = Document.GetElementsByTagName("Signature");
            // Remove existing signatures, this is not a countersigning.
            for (int i = 0; i < SignaturesList.Count; i++)
            {
                SignaturesList[i].ParentNode.RemoveChild(SignaturesList[i]);
                i--;
            }

            SignedXml SignedXml = new SignedXml(Document);
            SignedXml.SigningKey = certificate.PrivateKey;
            Reference Reference = new Reference();
            Reference.Uri = "";
            XmlDsigEnvelopedSignatureTransform EnvelopedSignatureTransform = new XmlDsigEnvelopedSignatureTransform();
            Reference.AddTransform(EnvelopedSignatureTransform);
            SignedXml.AddReference(Reference);
            KeyInfo Key = new KeyInfo();
            Key.AddClause(new KeyInfoX509Data(certificate));
            SignedXml.KeyInfo = Key;
            SignedXml.ComputeSignature();
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement XmlDigitalSignature = SignedXml.GetXml();

            return XmlDigitalSignature;
        }
开发者ID:usnistgov,项目名称:DT4SM,代码行数:32,代码来源:XML4PLOT.cs

示例2: SignXml

        private static string SignXml(XmlDocument unsignedXml,
                                        AsymmetricAlgorithm key)
        {
            if (unsignedXml.DocumentElement == null)
            {
                throw new ArgumentNullException("unsignedXml");
            }

            // Create a reference to be signed. Blank == Everything
                var emptyReference = new Reference { Uri = "" };

            // Add an enveloped transformation to the reference.
            var envelope = new XmlDsigEnvelopedSignatureTransform();
            emptyReference.AddTransform(envelope);

            var signedXml = new SignedXml(unsignedXml) { SigningKey = key };
            signedXml.AddReference(emptyReference);
            signedXml.ComputeSignature();

            var digitalSignature = signedXml.GetXml();
       
                unsignedXml.DocumentElement.AppendChild(
                    unsignedXml.ImportNode(digitalSignature, true));

            var signedXmlOut = new StringBuilder();
            using (var swOut = new StringWriter(signedXmlOut))
            {
                unsignedXml.Save(swOut);
            }

            return signedXmlOut.ToString();
        }
开发者ID:huoxudong125,项目名称:HQF.Tutorial.Encryption,代码行数:32,代码来源:SignAndVerify.cs

示例3: SignXml

        // Sign an XML file.  
        // This document cannot be verified unless the verifying  
        // code has the key with which it was signed. 
        public static void SignXml(XmlDocument xmlDoc, RSA Key)
        {
            // Check arguments. 
            if (xmlDoc == null)
                throw new ArgumentException("xmlDoc");
            if (Key == null)
                throw new ArgumentException("Key");

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(xmlDoc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;

            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save 
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // Append the element to the XML document.
            xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        }
开发者ID:duyisu,项目名称:MissionPlanner,代码行数:38,代码来源:SignXML.cs

示例4: Sign

        public static string Sign(string xml, X509Certificate2 certificate)
        {
            if (xml == null) throw new ArgumentNullException("xml");
            if (certificate == null) throw new ArgumentNullException("certificate");
            if (!certificate.HasPrivateKey) throw new ArgumentException("Certificate should have a private key", "certificate");

            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(xml);

            SignedXml signedXml = new SignedXml(doc);
            signedXml.SigningKey = certificate.PrivateKey;

            // Attach certificate KeyInfo
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(certificate);
            KeyInfo keyInfo = new KeyInfo();
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // Attach transforms
            var reference = new Reference("");
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform(includeComments: false));
            reference.AddTransform(new XmlDsigExcC14NTransform(includeComments: false));
            signedXml.AddReference(reference);

            // Compute signature
            signedXml.ComputeSignature();
            var signatureElement = signedXml.GetXml();

            // Add signature to bundle
            doc.DocumentElement.AppendChild(doc.ImportNode(signatureElement, true));

            return doc.OuterXml;
        }
开发者ID:Condeti,项目名称:spark,代码行数:35,代码来源:XmlSignatureHelper.cs

示例5: CertificateChain

        /// <summary>
        /// Creates a chain of X509Certificates given the provided XML-DSig.
        /// </summary>
        /// <param name="xmlDoc">XML-Dsig used to create the chain.</param>
        /// <returns>Chain of X509Certificates</returns>
        public static List<X509Certificate2> CertificateChain(string xmlDoc)
        {
            if (xmlDoc == null)
            {
                throw new ArgumentException("xmlDoc was null");
            }
            var xml = XmlUtil.LoadXml(xmlDoc);
            var xmlNamespaces = new XmlNamespaceManager(xml.NameTable);
            xmlNamespaces.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            var sigElement = (XmlElement)xml.SelectSingleNode("//ds:Signature[1]", xmlNamespaces);
            var signature = new SignedXml(xml);
            signature.LoadXml(sigElement);

            var certificates = new List<X509Certificate2>();
            foreach (var clause in signature.KeyInfo)
            {
                if (!(clause is KeyInfoX509Data)) continue;
                foreach (var x509Cert in ((KeyInfoX509Data)clause).Certificates)
                {
                    certificates.Add((X509Certificate2)x509Cert);
                }
            }

            return certificates;
        }
开发者ID:hgaard,项目名称:OOAPI,代码行数:31,代码来源:XmlDsigParser.cs

示例6: VerifyXml

            public void VerifyXml(string xml)
            {
                var doc = LoadXmlDoc(xml);

                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.FromXmlString(publicKey);

                    var nsMgr = new XmlNamespaceManager(doc.NameTable);
                    nsMgr.AddNamespace("sig", "http://www.w3.org/2000/09/xmldsig#");

                    var signedXml = new SignedXml(doc);
                    var signature = (XmlElement)doc.SelectSingleNode("//sig:Signature", nsMgr);
                    if (signature == null)
                    {
                        throw new Exception("Xml is invalid as it has no XML signature");
                    }
                    signedXml.LoadXml(signature);

                    if (!signedXml.CheckSignature(rsa))
                    {
                        throw new Exception("Xml is invalid as it failed signature check.");
                    }
                }
            }
开发者ID:Particular,项目名称:ServiceInsight,代码行数:25,代码来源:LicenseVerifier.cs

示例7: Sign

        public static void Sign(this XmlDocument xmlDocument, X509Certificate2 cert)
        {
            if (xmlDocument == null)
            {
                throw new ArgumentNullException("xmlDocument");
            }

            if (cert == null)
            {
                throw new ArgumentNullException("cert");
            }

            var signedXml = new SignedXml(xmlDocument);

            // The transform XmlDsigExcC14NTransform and canonicalization method XmlDsigExcC14NTransformUrl is important for partially signed XML files
            // see: http://msdn.microsoft.com/en-us/library/system.security.cryptography.xml.signedxml.xmldsigexcc14ntransformurl(v=vs.110).aspx
            // The reference URI has to be set correctly to avoid assertion injections
            // For both, the ID/Reference and the Transform/Canonicalization see as well: 
            // https://www.oasis-open.org/committees/download.php/35711/sstc-saml-core-errata-2.0-wd-06-diff.pdf section 5.4.2 and 5.4.3

            signedXml.SigningKey = (RSACryptoServiceProvider)cert.PrivateKey;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            var reference = new Reference { Uri = "#" + xmlDocument.DocumentElement.GetAttribute("ID") };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());

            signedXml.AddReference(reference);
            signedXml.ComputeSignature();

            xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signedXml.GetXml(), true));
        }
开发者ID:dmarlow,项目名称:authservices,代码行数:32,代码来源:XmlDocumentExtensions.cs

示例8: SignRequestXml

        /// <summary>
        /// Adds a digital signature to the outgoing request message, before sending it to Acquirer.
        /// </summary>
        /// <param name="requestXml">
        /// The unsigned request XML message.
        /// </param>
        /// <returns>
        /// The request message, including digital signature.
        /// </returns>
        public string SignRequestXml(XDocument requestXml)
        {
            XmlDocument document = ToXmlDocument(requestXml);

            RSACryptoServiceProvider key = ExtractPrivateKeyFrom(acceptantPrivateCertificate);

            var signedXml = new SignedXml(document) { SigningKey = key };
            signedXml.SignedInfo.SignatureMethod = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
            signedXml.SignedInfo.CanonicalizationMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";

            // Add a signing reference, the uri is empty and so the whole document is signed. 
            var reference = new Reference { DigestMethod = @"http://www.w3.org/2001/04/xmlenc#sha256" };
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.Uri = "";
            signedXml.AddReference(reference);

            // Add the certificate as key info. Because of this, the certificate 
            // with the public key will be added in the signature part. 
            var keyInfo = new KeyInfo();
            keyInfo.AddClause(new KeyInfoName(acceptantPrivateCertificate.Thumbprint));
            signedXml.KeyInfo = keyInfo;

            // Generate the signature. 
            signedXml.ComputeSignature();

            XmlElement xmlSignature = signedXml.GetXml();
            document.DocumentElement.AppendChild(document.ImportNode(xmlSignature, true));

            // Check that outgoing signature is valid. Private certificate also contains public part.
            VerifyDocumentSignature(document, acceptantPrivateCertificate);

            return GetContentsFrom(document);
        }
开发者ID:bkoelman,项目名称:iDeal.Net,代码行数:42,代码来源:SignatureProvider.cs

示例9: AppendSignatureToXMLDocument

        /// <summary>
        /// Use an X509 certificate to append a computed signature to an XML serialized Response
        /// </summary>
        /// <param name="XMLSerializedSAMLResponse"></param>
        /// <param name="ReferenceURI">Assertion ID from SAML Response</param>
        /// <param name="SigningCert">X509 Certificate for signing</param>
        /// <remarks>Referenced this article:
        ///     http://www.west-wind.com/weblog/posts/2008/Feb/23/Digitally-Signing-an-XML-Document-and-Verifying-the-Signature
        /// </remarks>
        public static void AppendSignatureToXMLDocument(ref XmlDocument XMLSerializedSAMLResponse, String ReferenceURI, X509Certificate2 SigningCert)
        {
            XmlNamespaceManager ns = new XmlNamespaceManager(XMLSerializedSAMLResponse.NameTable);
            ns.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            XmlElement xeAssertion = XMLSerializedSAMLResponse.DocumentElement.SelectSingleNode("saml:Assertion", ns) as XmlElement;

            //SignedXml signedXML = new SignedXml(XMLSerializedSAMLResponse);
            SignedXml signedXML = new SignedXml(xeAssertion);

            signedXML.SigningKey = SigningCert.PrivateKey;
            signedXML.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;

            Reference reference = new Reference();
            reference.Uri = ReferenceURI;
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            reference.AddTransform(new XmlDsigExcC14NTransform());
            signedXML.AddReference(reference);
            signedXML.ComputeSignature();

            XmlElement signature = signedXML.GetXml();

            XmlElement xeResponse = XMLSerializedSAMLResponse.DocumentElement;

            xeResponse.AppendChild(signature);
        }
开发者ID:DodgeDerek,项目名称:saml-http-post-reference,代码行数:34,代码来源:CertificateUtility.cs

示例10: VerifyDigitalSignature

        /// <summary>
        /// Verifies the digital signature.
        /// </summary>
        /// <param name="digitalSignature"> The XML Digital Signature.</param>
        /// <param name="publicKey"> The RSA public key.</param>
        /// <returns> Returns true if valid, else false.</returns>
        public static bool VerifyDigitalSignature(XmlTextReader digitalSignature, RSA publicKey)
        {
            bool valid = false;
            try
            {
                // Load license file into XmlDocument
                XmlDocument doc = new XmlDocument();
                doc.Load(digitalSignature);

                // Load Signature Element
                SignedXml verifier = new SignedXml(doc);
                verifier.LoadXml(doc.GetElementsByTagName("Signature")[0] as XmlElement);

                // Validate license.
                if ( verifier.CheckSignature(publicKey) )
                {
                    valid = true;
                }
                else
                {
                    valid = false;
                }
            }
            catch
            {
                valid = false;
            }

            return valid;
        }
开发者ID:molekilla,项目名称:Ecyware_GreenBlue_Inspector,代码行数:36,代码来源:DigitalSignatureVerifier.cs

示例11: IsSignedByAny

        /// <summary>
        /// Checks if an xml element is signed by the given certificate, through
        /// a contained enveloped signature.
        /// </summary>
        /// <param name="xmlElement">Xml Element that should be signed</param>
        /// <param name="signingKeys">Signing keys to test, one should validate.</param>
        /// <param name="validateCertificate">Should the certificate be validated too?</param>
        /// <returns>True on correct signature, false on missing signature</returns>
        /// <exception cref="InvalidSignatureException">If the data has
        /// been tampered with or is not valid according to the SAML spec.</exception>
        public static bool IsSignedByAny(
            this XmlElement xmlElement, 
            IEnumerable<SecurityKeyIdentifierClause> signingKeys,
            bool validateCertificate)
        {
            if (xmlElement == null)
            {
                throw new ArgumentNullException(nameof(xmlElement));
            }

            var signedXml = new SignedXml(xmlElement);

            var signatureElement = xmlElement["Signature", SignedXml.XmlDsigNamespaceUrl];

            if (signatureElement == null)
            {
                return false;
            }

            signedXml.LoadXml(signatureElement);
            ValidateSignedInfo(signedXml, xmlElement);
            VerifySignature(signingKeys, signedXml, signatureElement, validateCertificate);

            return true;
        }
开发者ID:woric,项目名称:authservices,代码行数:35,代码来源:XmlHelpers.cs

示例12: SignXmlDocument

        //        /// <summary>
        //        /// Signs a license.
        //        /// </summary>
        //        /// <param name="unsignedLicense"> The unsigned license stream.</param>
        //        /// <param name="keyPair"> The stream containing the private key file.</param>
        //        /// <param name="output"> The output stream containing the new signed license.</param>
        //        internal void SignLicense(XmlTextReader unsignedLicense, Stream keyPair, Stream output)
        //        {
        //            try
        //            {
        //                // setup the document to sign
        //                XmlDocument licenseDocument = new XmlDocument();
        //                licenseDocument.Load(unsignedLicense);
        //
        //                // read in the public key
        //                RSA signingKey = new RSACryptoServiceProvider();
        //                using(StreamReader reader = new StreamReader(keyPair))
        //                {
        //                    signingKey.FromXmlString(reader.ReadLine());
        //                }
        //
        //                // now sign the document
        //                SignedXml signer = new SignedXml(licenseDocument);
        //                signer.SigningKey = signingKey;
        //
        //                // create a reference to the root of the document
        //                Reference orderRef = new Reference("");
        //                orderRef.AddTransform(new XmlDsigEnvelopedSignatureTransform());
        //                signer.AddReference(orderRef);
        //
        //                // add transforms that only select the order items, type, and
        //                // compute the signature, and add it to the document
        //                signer.ComputeSignature();
        //                licenseDocument.DocumentElement.AppendChild(signer.GetXml());
        //
        //                licenseDocument.Save(output);
        //            }
        //            catch
        //            {
        //                throw;
        //            }
        //        }
        /// <summary>
        /// Signs the XmlDocument.
        /// </summary>
        /// <param name="document"> The XmlDocument to sign.</param>
        /// <param name="signingKey"> The signing key.</param>
        /// <returns> A signed XmlDocument.</returns>
        internal XmlDocument SignXmlDocument(XmlDocument document, RSA signingKey)
        {
            try
            {
            //				// setup the document to sign
            //				XmlDocument licenseDocument = new XmlDocument();
            //				licenseDocument.Load(unsignedLicense);

                // now sign the document
                SignedXml signer = new SignedXml(document);
                signer.SigningKey = signingKey;

                // create a reference to the root of the document
                Reference reference = new Reference("");
                reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
                signer.AddReference(reference);

                // compute the signature, and add it to the document
                signer.ComputeSignature();
                document.DocumentElement.AppendChild(signer.GetXml());

                return document;
            }
            catch
            {
                throw;
            }
        }
开发者ID:molekilla,项目名称:Ecyware_GreenBlue_Inspector,代码行数:76,代码来源:XmlSignature.cs

示例13: AddSignedXml

        void AddSignedXml() {
            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(this.XmlDoc);
            // Add the key to the SignedXml document. 
            signedXml.SigningKey = SigningCertificate.PrivateKey;

            // http://stackoverflow.com/questions/13750343/net-signedxml-signing-xml-with-transform-algorithm-exc-c14n
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            // Create a reference to be signed.
            Reference reference = new Reference() {
                Uri = "#" + Id
            };
            // Add an enveloped transformation to the reference.
            reference.AddTransform(new XmlDsigEnvelopedSignatureTransform());
            //canonicalize
            reference.AddTransform(new XmlDsigExcC14NTransform());
            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
            KeyInfo keyInfo = new KeyInfo();
            KeyInfoX509Data keyInfoData = new KeyInfoX509Data(SigningCertificate);
            keyInfo.AddClause(keyInfoData);
            signedXml.KeyInfo = keyInfo;

            // Compute the signature.
            signedXml.ComputeSignature();
            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();
            // Append the element to the XML document.
            this.XmlDoc.DocumentElement.AppendChild(this.XmlDoc.ImportNode(xmlDigitalSignature, true));
        }
开发者ID:RunLola,项目名称:Practices.IdentityProvider,代码行数:33,代码来源:AuthnRequest.cs

示例14: ValidateLicenseXml

        public LicenseDetails ValidateLicenseXml(string xml)
        {
            var doc = new XmlDocument();
            using (TextReader reader = new StringReader(xml))
            {
                try
                {
                    doc.Load(reader);
                }
                catch
                {
                    throw new InvalidLicenseXmlException();
                }

                // Validate the xml's signature
                var signedXml = new SignedXml(doc);
                var nodeList = doc.GetElementsByTagName("Signature");
                if (nodeList.Count == 0)
                    throw new LicenseSignatureMissingException();

                signedXml.LoadXml((XmlElement) nodeList[0]);
                if (!signedXml.CheckSignature(_key))
                    throw new LicenseSignatureMismatchException();
            }

            // Deserialize the xml
            var deserializer = new XmlSerializer(typeof(LicenseDetails));
            using (TextReader reader = new StringReader(xml))
                return (LicenseDetails) deserializer.Deserialize(reader);
        }
开发者ID:KallDrexx,项目名称:ELiS,代码行数:30,代码来源:LicenseValidator.cs

示例15: ExtractSignature

 /// <summary>
 /// Gets the signature from an XmlDocument.
 /// </summary>
 /// <param name="xmlDocument">The source XmlDocument.</param>
 /// <returns>A SignedXml object representing the signature.</returns>
 private static SignedXml ExtractSignature(XmlDocument xmlDocument)
 {
     var signedXml = new SignedXml(xmlDocument);
     XmlNodeList nodeList = xmlDocument.GetElementsByTagName("Signature");
     signedXml.LoadXml((XmlElement)nodeList[0]);
     return signedXml;
 }
开发者ID:rickeygalloway,项目名称:Test,代码行数:12,代码来源:SignatureVerifier.cs


注:本文中的System.Security.Cryptography.Xml.SignedXml类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。