public void Signature2 () { SignedInfo info = new SignedInfo (); signature.SignedInfo = info; info.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; signature.SignatureValue = new byte [128]; // no reference element are present XmlElement xel = signature.GetXml (); }
/// <summary> /// Log that checking SignedInfo is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="signedInfo">SignedInfo object being verified</param> internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signedInfo != null, " signedInfo != null"); if (InformationLoggingEnabled) { string logMessage = String.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_CheckSignedInfo"), signedInfo.Id != null ? signedInfo.Id : NullString); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage); } }
/// <summary> /// Log that checking SignedInfo is beginning /// </summary> /// <param name="signedXml">SignedXml object doing the verification</param> /// <param name="signedInfo">SignedInfo object being verified</param> internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo) { Debug.Assert(signedXml != null, "signedXml != null"); Debug.Assert(signedInfo != null, " signedInfo != null"); if (InformationLoggingEnabled) { string logMessage = SR.Format(CultureInfo.InvariantCulture, SR.Log_CheckSignedInfo, signedInfo.Id ?? NullString); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, logMessage); } }
public void SignatureLength () { // we can set the length before the algorithm SignedInfo si = new SignedInfo (); si.SignatureLength = "128"; Assert.AreEqual ("128", si.SignatureLength, "SignatureLength-1"); Assert.IsNull (si.SignatureMethod, "SignatureMethod-1"); // zero si.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; si.SignatureLength = "0"; Assert.AreEqual ("0", si.SignatureLength, "SignatureLength-2"); Assert.AreEqual ("http://www.w3.org/2000/09/xmldsig#rsa-sha1", si.SignatureMethod, "SignatureMethod-2"); // mixup length and method si.SignatureLength = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; si.SignatureMethod = "0"; Assert.AreEqual ("http://www.w3.org/2000/09/xmldsig#rsa-sha1", si.SignatureLength, "SignatureLength-3"); Assert.AreEqual ("0", si.SignatureMethod, "SignatureMethod-3"); }
/// <summary> /// Verify the transforms on a strong name signature are valid for a ClickOnce manifest. /// </summary> /// <remarks> /// For a reference to the entire document, we expect both exclusive cannonicalization and /// enveloped transform. For a reference to the strong name key section, we expect only exclusive /// cannonicalization. Other references are not given special meaning for a strong name signature /// and are ignored. Failure to have exactly the correct set of transforms is an error with the /// strong name signature. /// </remarks> private static SignatureVerificationResult VerifyStrongNameSignatureTransforms(SignedInfo signedInfo) { Debug.Assert(signedInfo != null, "signedInfo != null"); int totalReferences = 0; foreach (Reference reference in signedInfo.References) { TransformChain transforms = reference.TransformChain; bool validTransformChain = false; if (String.IsNullOrEmpty(reference.Uri)) { totalReferences++; validTransformChain = transforms != null && transforms.Count == 2 && String.Compare(transforms[0].Algorithm, SignedXml.XmlDsigEnvelopedSignatureTransformUrl, StringComparison.Ordinal) == 0 && String.Compare(transforms[1].Algorithm, SignedXml.XmlDsigExcC14NTransformUrl, StringComparison.Ordinal) == 0; } else if (String.Compare(reference.Uri, "#StrongNameKeyInfo", StringComparison.Ordinal) == 0) { totalReferences++; validTransformChain = transforms != null && transforms.Count == 1 && String.Compare(transforms[0].Algorithm, SignedXml.XmlDsigExcC14NTransformUrl, StringComparison.Ordinal) == 0; } else { validTransformChain = true; } if (!validTransformChain) { return SignatureVerificationResult.BadSignatureFormat; } } if (totalReferences == 0) { return SignatureVerificationResult.BadSignatureFormat; } return SignatureVerificationResult.Valid; }
private static SignatureVerificationResult VerifyStrongNameSignatureTransforms(SignedInfo signedInfo) { int num = 0; foreach (Reference reference in signedInfo.References) { TransformChain transformChain = reference.TransformChain; bool flag = false; if (string.IsNullOrEmpty(reference.Uri)) { num++; flag = (((transformChain != null) && (transformChain.Count == 2)) && (string.Compare(transformChain[0].Algorithm, "http://www.w3.org/2000/09/xmldsig#enveloped-signature", StringComparison.Ordinal) == 0)) && (string.Compare(transformChain[1].Algorithm, "http://www.w3.org/2001/10/xml-exc-c14n#", StringComparison.Ordinal) == 0); } else if (string.Compare(reference.Uri, "#StrongNameKeyInfo", StringComparison.Ordinal) == 0) { num++; flag = ((transformChain != null) && (transformChain.Count == 1)) && (string.Compare(transformChain[0].Algorithm, "http://www.w3.org/2001/10/xml-exc-c14n#", StringComparison.Ordinal) == 0); } else { flag = true; } if (!flag) { return SignatureVerificationResult.BadSignatureFormat; } } if (num == 0) { return SignatureVerificationResult.BadSignatureFormat; } return SignatureVerificationResult.Valid; }
protected void SetUp () { info = new SignedInfo (); }
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); }
/// <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()); }
/// <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()); }
private static SignatureVerificationResult VerifyStrongNameSignatureTransforms(SignedInfo signedInfo) { int num = 0; foreach (Reference reference in signedInfo.References) { TransformChain transformChain = reference.TransformChain; bool flag = false; if (string.IsNullOrEmpty(reference.Uri)) { num++; flag = (((transformChain != null) && (transformChain.Count == 2)) && (string.Compare(transformChain[0].Algorithm, "http://www.w3.org/2000/09/xmldsig#enveloped-signature", StringComparison.Ordinal) == 0)) && (string.Compare(transformChain[1].Algorithm, "http://www.w3.org/2001/10/xml-exc-c14n#", StringComparison.Ordinal) == 0); } else if (string.Compare(reference.Uri, "#StrongNameKeyInfo", StringComparison.Ordinal) == 0) { num++; flag = ((transformChain != null) && (transformChain.Count == 1)) && (string.Compare(transformChain[0].Algorithm, "http://www.w3.org/2001/10/xml-exc-c14n#", StringComparison.Ordinal) == 0); } else { flag = true; } if (!flag) { return(SignatureVerificationResult.BadSignatureFormat); } } if (num == 0) { return(SignatureVerificationResult.BadSignatureFormat); } return(SignatureVerificationResult.Valid); }
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"); }
internal static void LogBeginCheckSignedInfo(SignedXml signedXml, SignedInfo signedInfo) { if (InformationLoggingEnabled) { string data = string.Format(CultureInfo.InvariantCulture, SecurityResources.GetResourceString("Log_CheckSignedInfo"), new object[] { (signedInfo.Id != null) ? signedInfo.Id : "(null)" }); WriteLine(signedXml, TraceEventType.Information, SignedXmlDebugEvent.BeginCheckSignedInfo, data); } }
/// <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); } } }
/// <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 }
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); }
/// <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 }
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 LoadXml(XmlElement value) { // Make sure we don't get passed null if (value == null) { throw new ArgumentNullException(nameof(value)); } // Signature XmlElement signatureElement = value; if (!signatureElement.LocalName.Equals("Signature")) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } // Id attribute -- optional _id = Utils.GetAttribute(signatureElement, "Id", SignedXml.XmlDsigNamespaceUrl); if (!Utils.VerifyAttributes(signatureElement, "Id")) { throw new CryptographicException(SR.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 || signedInfoNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignedInfo"); } XmlElement signedInfoElement = signedInfoNodes[0] as XmlElement; expectedChildNodes += signedInfoNodes.Count; SignedInfo = new SignedInfo(); SignedInfo.LoadXml(signedInfoElement); // SignatureValue XmlNodeList signatureValueNodes = signatureElement.SelectNodes("ds:SignatureValue", nsm); if (signatureValueNodes == null || signatureValueNodes.Count == 0 || signatureValueNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); } XmlElement signatureValueElement = signatureValueNodes[0] as XmlElement; expectedChildNodes += signatureValueNodes.Count; _signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText)); _signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl); if (!Utils.VerifyAttributes(signatureValueElement, "Id")) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "SignatureValue"); } // KeyInfo - optional single element XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); _keyInfo = new KeyInfo(); if (keyInfoNodes != null) { if (keyInfoNodes.Count > 1) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "KeyInfo"); } foreach (XmlNode node in keyInfoNodes) { XmlElement keyInfoElement = node as XmlElement; if (keyInfoElement != null) { _keyInfo.LoadXml(keyInfoElement); } } expectedChildNodes += keyInfoNodes.Count; } // Object - zero or more elements allowed XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); _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); _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) { _referencedItems.Add(node); } } // Verify that there aren't any extra nodes that aren't allowed if (signatureElement.SelectNodes("*").Count != expectedChildNodes) { throw new CryptographicException(SR.Cryptography_Xml_InvalidElement, "Signature"); } }
/// <summary> /// Verify the transforms on a strong name signature are valid for a ClickOnce manifest. /// </summary> /// <remarks> /// For a reference to the entire document, we expect both exclusive cannonicalization and /// enveloped transform. For a reference to the strong name key section, we expect only exclusive /// cannonicalization. Other references are not given special meaning for a strong name signature /// and are ignored. Failure to have exactly the correct set of transforms is an error with the /// strong name signature. /// </remarks> private static SignatureVerificationResult VerifyStrongNameSignatureTransforms(SignedInfo signedInfo) { Debug.Assert(signedInfo != null, "signedInfo != null"); int totalReferences = 0; foreach (Reference reference in signedInfo.References) { TransformChain transforms = reference.TransformChain; bool validTransformChain = false; if (String.IsNullOrEmpty(reference.Uri)) { totalReferences++; validTransformChain = transforms != null && transforms.Count == 2 && String.Compare(transforms[0].Algorithm, SignedXml.XmlDsigEnvelopedSignatureTransformUrl, StringComparison.Ordinal) == 0 && String.Compare(transforms[1].Algorithm, SignedXml.XmlDsigExcC14NTransformUrl, StringComparison.Ordinal) == 0; } else if (String.Compare(reference.Uri, "#StrongNameKeyInfo", StringComparison.Ordinal) == 0) { totalReferences++; validTransformChain = transforms != null && transforms.Count == 1 && String.Compare(transforms[0].Algorithm, SignedXml.XmlDsigExcC14NTransformUrl, StringComparison.Ordinal) == 0; } else { validTransformChain = true; } if (!validTransformChain) { return(SignatureVerificationResult.BadSignatureFormat); } } if (totalReferences == 0) { return(SignatureVerificationResult.BadSignatureFormat); } return(SignatureVerificationResult.Valid); }
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 _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"); } SignedInfo = new SignedInfo(); 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"); } _signatureValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(signatureValueElement.InnerText)); _signatureValueId = Utils.GetAttribute(signatureValueElement, "Id", SignedXml.XmlDsigNamespaceUrl); XmlNodeList keyInfoNodes = signatureElement.SelectNodes("ds:KeyInfo", nsm); _keyInfo = new KeyInfo(); if (keyInfoNodes != null) { foreach (XmlNode node in keyInfoNodes) { XmlElement keyInfoElement = node as XmlElement; if (keyInfoElement != null) { _keyInfo.LoadXml(keyInfoElement); } } } XmlNodeList objectNodes = signatureElement.SelectNodes("ds:Object", nsm); _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); _embeddedObjects.Add(dataObj); } } } // Select all elements that have Id attributes XmlNodeList nodeList = signatureElement.SelectNodes("//*[@Id]", nsm); if (nodeList != null) { foreach (XmlNode node in nodeList) { _referencedItems.Add(node); } } }