public void GetXmlWithSetProperty ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (xmlForGetXml);
			SignedInfo sig = new SignedInfo ();
			sig.LoadXml ((XmlElement) doc.SelectSingleNode ("//*[local-name()='SignedInfo']"));
			sig.CanonicalizationMethod = "urn:foo";
			XmlElement el = sig.GetXml ();
			Assert ("#GetXmlWithSetProperty.document", doc != el.OwnerDocument);
		}
		public void EmptyReferenceWithSetProperty ()
		{
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (xmlForGetXml);
			XmlNode n = doc.SelectSingleNode ("//*[local-name()='Reference']");
			n.ParentNode.RemoveChild (n);

			SignedInfo sig = new SignedInfo ();
			sig.LoadXml ((XmlElement) doc.SelectSingleNode ("//*[local-name()='SignedInfo']"));
			sig.CanonicalizationMethod = "urn:foo";
			XmlElement el = sig.GetXml ();
		}
		public void GetXmlWithoutSetProperty ()
		{
			string result = @"<dsig:SignedInfo xmlns:dsig=""http://www.w3.org/2000/09/xmldsig#""><dsig:CanonicalizationMethod Algorithm=""http://www.w3.org/TR/2001/REC-xml-c14n-withcomments-20010315"" /><dsig:SignatureMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#rsa-sha1"" /><dsig:Reference URI=""""><dsig:Transforms><dsig:Transform Algorithm=""http://www.w3.org/2000/09/xmldsig#enveloped-signature"" /></dsig:Transforms><dsig:DigestMethod Algorithm=""http://www.w3.org/2000/09/xmldsig#sha1"" /><dsig:DigestValue>nDF2V/bzRd0VE3EwShWtsBzTEDc=</dsig:DigestValue></dsig:Reference></dsig:SignedInfo>";
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml (xmlForGetXml);
			SignedInfo sig = new SignedInfo ();
			sig.LoadXml ((XmlElement) doc.SelectSingleNode ("//*[local-name()='SignedInfo']"));
			XmlElement el = sig.GetXml ();
			AssertEquals ("#GetXmlWOSetProperty.document", doc, el.OwnerDocument);
			AssertEquals ("#GetXmlWOSetProperty.outerxml", result, el.OuterXml);
		}
Exemplo n.º 4
0
        /// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.ComputeSignature1"]/*' />
        public void ComputeSignature(KeyedHashAlgorithm macAlg)
        {
            // Do some sanity checks
            if (macAlg == null)
            {
                throw new ArgumentNullException("macAlg");
            }
            if (!(macAlg is HMACSHA1))
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureMethodKeyMismatch"));
            }
            int iSignatureLength;

            if (m_signature.SignedInfo.SignatureLength == null)
            {
                iSignatureLength = macAlg.HashSize;
            }
            else
            {
                iSignatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength);
            }
            // iSignatureLength should be less than hash size
            if (iSignatureLength < 0 || iSignatureLength > macAlg.HashSize)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength"));
            }
            if (iSignatureLength % 8 != 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2"));
            }

            BuildDigestedReferences();
            SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
            // Compute the hash of the SignedInfo object
            XmlElement signedInfo = SignedInfo.GetXml().Clone() as XmlElement;

            // Add non default namespaces in scope
            if (m_namespaces != null)
            {
                foreach (XmlNode attrib in m_namespaces)
                {
                    string name = ((attrib.Prefix != String.Empty) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName);
                    // Skip the attribute if one with the same qualified name already exists
                    if (signedInfo.HasAttribute(name) || (name.Equals("xmlns") && signedInfo.NamespaceURI != String.Empty))
                    {
                        continue;
                    }
                    XmlAttribute nsattrib = m_containingDocument.CreateAttribute(name);
                    nsattrib.Value = ((XmlNode)attrib).Value;
                    signedInfo.SetAttributeNode(nsattrib);
                }
            }
#if _DEBUG
            if (debug)
            {
                Console.WriteLine("computed signedInfo: ");
                Console.WriteLine(signedInfo.OuterXml);
            }
#endif
            TransformChain tc = new TransformChain();
            Transform      c14nMethodTransform = (Transform)CryptoConfig.CreateFromName(SignedInfo.CanonicalizationMethod);
            if (c14nMethodTransform == null)
            {
                throw new CryptographicException(String.Format(SecurityResources.GetResourceString("Cryptography_Xml_CreateTransformFailed"), SignedInfo.CanonicalizationMethod));
            }
            tc.Add(c14nMethodTransform);
            string      strBaseUri = (m_containingDocument == null ? null : m_containingDocument.BaseURI);
            XmlResolver resolver   = (m_bResolverSet ? m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), strBaseUri));
            Stream      hashInput  = tc.TransformToOctetStream(PreProcessElementInput(signedInfo, resolver, strBaseUri), resolver, strBaseUri);
            byte[]      hashValue  = macAlg.ComputeHash(hashInput);
            m_signature.SignatureValue = new byte[iSignatureLength / 8];
            Buffer.BlockCopy(hashValue, 0, m_signature.SignatureValue, 0, iSignatureLength / 8);
#if _DEBUG
            if (debug)
            {
                Console.WriteLine("computed hash value: " + Convert.ToBase64String(hashValue));
            }
#endif
        }
Exemplo n.º 5
0
        /// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.ComputeSignature"]/*' />
        public void ComputeSignature()
        {
            BuildDigestedReferences();
            // Load the key
            AsymmetricAlgorithm key;

            if (SigningKey != null)
            {
                key = SigningKey;
            }
            else
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_LoadKeyFailed"));
            }

            if (key == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_LoadKeyFailed"));
            }

            // Check the signature algorithm associated with the key so that we can accordingly set
            // the signature method
            if (key is DSA)
            {
                SignedInfo.SignatureMethod = XmlDsigDSAUrl;
            }
            else if (key is RSA)
            {
                // Default to RSA-SHA1
                if (SignedInfo.SignatureMethod == null)
                {
                    SignedInfo.SignatureMethod = XmlDsigRSASHA1Url;
                }
            }
            else
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreatedKeyFailed"));
            }
            // Compute the hash of the SignedInfo object
            XmlElement signedInfo = SignedInfo.GetXml().Clone() as XmlElement;

            // Add non default namespaces in scope
            if (m_namespaces != null)
            {
                foreach (XmlNode attrib in m_namespaces)
                {
                    string name = ((attrib.Prefix != String.Empty) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName);
                    // Skip the attribute if one with the same qualified name already exists
                    if (signedInfo.HasAttribute(name) || (name.Equals("xmlns") && signedInfo.NamespaceURI != String.Empty))
                    {
                        continue;
                    }
                    XmlAttribute nsattrib = m_containingDocument.CreateAttribute(name);
                    nsattrib.Value = ((XmlNode)attrib).Value;
                    signedInfo.SetAttributeNode(nsattrib);
                }
            }
#if _DEBUG
            if (debug)
            {
                Console.WriteLine("computed signedInfo: ");
                Console.WriteLine(signedInfo.OuterXml);
            }
#endif
            TransformChain tc = new TransformChain();
            Transform      c14nMethodTransform = (Transform)CryptoConfig.CreateFromName(SignedInfo.CanonicalizationMethod);
            if (c14nMethodTransform == null)
            {
                throw new CryptographicException(String.Format(SecurityResources.GetResourceString("Cryptography_Xml_CreateTransformFailed"), SignedInfo.CanonicalizationMethod));
            }
            tc.Add(c14nMethodTransform);
            string      strBaseUri = (m_containingDocument == null ? null : m_containingDocument.BaseURI);
            XmlResolver resolver   = (m_bResolverSet ? m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), strBaseUri));
            Stream      hashInput  = tc.TransformToOctetStream(PreProcessElementInput(signedInfo, resolver, strBaseUri), resolver, strBaseUri);

            // See if there is a signature description class defined through the Config file
            SignatureDescription signatureDescription = (SignatureDescription)CryptoConfig.CreateFromName(SignedInfo.SignatureMethod);
            if (signatureDescription == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated"));
            }
            // calculate the hash
            HashAlgorithm hashAlg = signatureDescription.CreateDigest();
            if (hashAlg == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }
            byte[] hashValue = hashAlg.ComputeHash(hashInput);
            AsymmetricSignatureFormatter asymmetricSignatureFormatter = signatureDescription.CreateFormatter(key);
            m_signature.SignatureValue = asymmetricSignatureFormatter.CreateSignature(hashAlg);
#if _DEBUG
            if (debug)
            {
                Console.WriteLine("computed hash value: " + Convert.ToBase64String(hashValue));
            }
#endif
        }
Exemplo n.º 6
0
        /// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.CheckSignature2"]/*' />
        public bool CheckSignature(KeyedHashAlgorithm macAlg)
        {
            // Do some sanity checks
            if (macAlg == null)
            {
                throw new ArgumentNullException("macAlg");
            }

            int iSignatureLength;

            if (m_signature.SignedInfo.SignatureLength == null)
            {
                iSignatureLength = macAlg.HashSize;
            }
            else
            {
                iSignatureLength = Convert.ToInt32(m_signature.SignedInfo.SignatureLength);
            }

            // iSignatureLength should be less than hash size
            if (iSignatureLength < 0 || iSignatureLength > macAlg.HashSize)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength"));
            }
            if (iSignatureLength % 8 != 0)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength2"));
            }
            if (m_signature.SignatureValue == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureValueRequired"));
            }
            if (m_signature.SignatureValue.Length != iSignatureLength / 8)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_InvalidSignatureLength"));
            }

            // set up the canonicalizer & canonicalize SignedInfo
            TransformChain tc = new TransformChain();
            Transform      c14nMethodTransform = (Transform)CryptoConfig.CreateFromName(SignedInfo.CanonicalizationMethod);

            if (c14nMethodTransform == null)
            {
                throw new CryptographicException(String.Format(SecurityResources.GetResourceString("Cryptography_Xml_CreateTransformFailed"), SignedInfo.CanonicalizationMethod));
            }
            tc.Add(c14nMethodTransform);
            XmlElement signedInfo = SignedInfo.GetXml().Clone() as XmlElement;

            // Add non default namespaces in scope
            if (m_namespaces != null)
            {
                foreach (XmlNode attrib in m_namespaces)
                {
                    string name = ((attrib.Prefix != String.Empty) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName);
                    // Skip the attribute if one with the same qualified name already exists
                    if (signedInfo.HasAttribute(name) || (name.Equals("xmlns") && signedInfo.NamespaceURI != String.Empty))
                    {
                        continue;
                    }
                    XmlAttribute nsattrib = m_containingDocument.CreateAttribute(name);
                    nsattrib.Value = ((XmlNode)attrib).Value;
                    signedInfo.SetAttributeNode(nsattrib);
                }
            }
            string      strBaseUri             = (m_containingDocument == null ? null : m_containingDocument.BaseURI);
            XmlResolver resolver               = (m_bResolverSet ? m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), strBaseUri));
            Stream      canonicalizedSignedXml = tc.TransformToOctetStream(PreProcessElementInput(signedInfo, resolver, strBaseUri), resolver, strBaseUri);

            // Calculate the hash
            byte[] hashValue = macAlg.ComputeHash(canonicalizedSignedXml);
#if _DEBUG
            if (debug)
            {
                Console.WriteLine("Computed canonicalized SignedInfo:");
                Console.WriteLine(signedInfo.OuterXml);
                Console.WriteLine("Computed Hash:");
                Console.WriteLine(Convert.ToBase64String(hashValue));
                Console.WriteLine("m_signature.SignatureValue:");
                Console.WriteLine(Convert.ToBase64String(m_signature.SignatureValue));
            }
#endif
            for (int i = 0; i < m_signature.SignatureValue.Length; i++)
            {
                if (m_signature.SignatureValue[i] != hashValue[i])
                {
                    return(false);
                }
            }

            return(CheckDigestedReferences());
        }
Exemplo n.º 7
0
        /// <include file='doc\SignedXml.uex' path='docs/doc[@for="SignedXml.CheckSignature1"]/*' />
        public bool CheckSignature(AsymmetricAlgorithm key)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }

            SignatureDescription signatureDescription = (SignatureDescription)CryptoConfig.CreateFromName(m_signature.SignedInfo.SignatureMethod);

            if (signatureDescription == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_SignatureDescriptionNotCreated"));
            }

            // Let's see if the key corresponds with the SignatureMethod
            Type ta = Type.GetType(signatureDescription.KeyAlgorithm);
            Type tb = key.GetType();

            if ((ta != tb) && !ta.IsSubclassOf(tb) && !tb.IsSubclassOf(ta))
            {
                // Signature method key mismatch
                return(false);
            }

            // set up the canonicalizer & canonicalize SignedInfo
            TransformChain tc = new TransformChain();
            Transform      c14nMethodTransform = (Transform)CryptoConfig.CreateFromName(SignedInfo.CanonicalizationMethod);

            if (c14nMethodTransform == null)
            {
                throw new CryptographicException(String.Format(SecurityResources.GetResourceString("Cryptography_Xml_CreateTransformFailed"), SignedInfo.CanonicalizationMethod));
            }
            tc.Add(c14nMethodTransform);
            XmlElement signedInfo = SignedInfo.GetXml().Clone() as XmlElement;

            // Add non default namespaces in scope
            if (m_namespaces != null)
            {
                foreach (XmlNode attrib in m_namespaces)
                {
                    string name = ((attrib.Prefix != String.Empty) ? attrib.Prefix + ":" + attrib.LocalName : attrib.LocalName);
                    // Skip the attribute if one with the same qualified name already exists
                    if (signedInfo.HasAttribute(name) || (name.Equals("xmlns") && signedInfo.NamespaceURI != String.Empty))
                    {
                        continue;
                    }
                    XmlAttribute nsattrib = m_containingDocument.CreateAttribute(name);
                    nsattrib.Value = ((XmlNode)attrib).Value;
                    signedInfo.SetAttributeNode(nsattrib);
                }
            }
            string      strBaseUri             = (m_containingDocument == null ? null : m_containingDocument.BaseURI);
            XmlResolver resolver               = (m_bResolverSet ? m_xmlResolver : new XmlSecureResolver(new XmlUrlResolver(), strBaseUri));
            Stream      canonicalizedSignedXml = tc.TransformToOctetStream(PreProcessElementInput(signedInfo, resolver, strBaseUri), resolver, strBaseUri);

            // calculate the hash
            HashAlgorithm hashAlgorithm = signatureDescription.CreateDigest();

            if (hashAlgorithm == null)
            {
                throw new CryptographicException(SecurityResources.GetResourceString("Cryptography_Xml_CreateHashAlgorithmFailed"));
            }
            byte[] hashval = hashAlgorithm.ComputeHash(canonicalizedSignedXml);

            // We can FINALLY generate the SignatureValue
#if _DEBUG
            if (debug)
            {
                Console.WriteLine("Computed canonicalized SignedInfo:");
                Console.WriteLine(signedInfo.OuterXml);
                Console.WriteLine("Computed Hash:");
                Console.WriteLine(Convert.ToBase64String(hashval));
                Console.WriteLine("m_signature.SignatureValue:");
                Console.WriteLine(Convert.ToBase64String(m_signature.SignatureValue));
            }
#endif
            AsymmetricSignatureDeformatter asymmetricSignatureDeformatter = signatureDescription.CreateDeformatter(key);
            bool bRet = asymmetricSignatureDeformatter.VerifySignature(hashAlgorithm, m_signature.SignatureValue);

            if (bRet != true)
            {
#if _DEBUG
                if (debug)
                {
                    Console.WriteLine("Failed to verify the signature on SignedInfo.");
                }
#endif
                return(false);
            }

            // Now is the time to go through all the references and see if their
            // DigestValue are good
            return(CheckDigestedReferences());
        }