SignedXml.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. //
  2. // SignedXml.cs - SignedXml implementation for XML Signature
  3. //
  4. // Author:
  5. // Sebastien Pouliot <[email protected]>
  6. // Atsushi Enomoto <[email protected]>
  7. // Tim Coleman <[email protected]>
  8. //
  9. // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
  10. // Copyright (C) Tim Coleman, 2004
  11. // (C) 2004 Novell (http://www.novell.com)
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System.Collections;
  34. using System.IO;
  35. using System.Runtime.InteropServices;
  36. using System.Security.Cryptography;
  37. using System.Security.Policy;
  38. using System.Net;
  39. using System.Text;
  40. using System.Xml;
  41. #if NET_2_0
  42. using System.Security.Cryptography.X509Certificates;
  43. #endif
  44. namespace System.Security.Cryptography.Xml {
  45. public class SignedXml {
  46. public const string XmlDsigCanonicalizationUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
  47. public const string XmlDsigCanonicalizationWithCommentsUrl = XmlDsigCanonicalizationUrl + "#WithComments";
  48. public const string XmlDsigDSAUrl = XmlDsigNamespaceUrl + "dsa-sha1";
  49. public const string XmlDsigHMACSHA1Url = XmlDsigNamespaceUrl + "hmac-sha1";
  50. public const string XmlDsigMinimalCanonicalizationUrl = XmlDsigNamespaceUrl + "minimal";
  51. public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#";
  52. public const string XmlDsigRSASHA1Url = XmlDsigNamespaceUrl + "rsa-sha1";
  53. public const string XmlDsigSHA1Url = XmlDsigNamespaceUrl + "sha1";
  54. #if NET_2_0
  55. public const string XmlDecryptionTransformUrl = "http://www.w3.org/2002/07/decrypt#XML";
  56. public const string XmlDsigBase64TransformUrl = XmlDsigNamespaceUrl + "base64";
  57. public const string XmlDsigC14NTransformUrl = XmlDsigCanonicalizationUrl;
  58. public const string XmlDsigC14NWithCommentsTransformUrl = XmlDsigCanonicalizationWithCommentsUrl;
  59. public const string XmlDsigEnvelopedSignatureTransformUrl = XmlDsigNamespaceUrl + "enveloped-signature";
  60. public const string XmlDsigExcC14NTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#";
  61. public const string XmlDsigExcC14NWithCommentsTransformUrl = XmlDsigExcC14NTransformUrl + "WithComments";
  62. public const string XmlDsigXPathTransformUrl = "http://www.w3.org/TR/1999/REC-xpath-19991116";
  63. public const string XmlDsigXsltTransformUrl = "http://www.w3.org/TR/1999/REC-xslt-19991116";
  64. private EncryptedXml encryptedXml;
  65. #endif
  66. protected Signature m_signature;
  67. private AsymmetricAlgorithm key;
  68. protected string m_strSigningKeyName;
  69. private XmlDocument envdoc;
  70. private IEnumerator pkEnumerator;
  71. private XmlElement signatureElement;
  72. private Hashtable hashes;
  73. // FIXME: enable it after CAS implementation
  74. #if false //NET_1_1
  75. private XmlResolver xmlResolver = new XmlSecureResolver (new XmlUrlResolver (), new Evidence ());
  76. #else
  77. private XmlResolver xmlResolver = new XmlUrlResolver ();
  78. #endif
  79. private ArrayList manifests;
  80. private static readonly char [] whitespaceChars = new char [] {' ', '\r', '\n', '\t'};
  81. public SignedXml ()
  82. {
  83. m_signature = new Signature ();
  84. m_signature.SignedInfo = new SignedInfo ();
  85. hashes = new Hashtable (2); // 98% SHA1 for now
  86. }
  87. public SignedXml (XmlDocument document) : this ()
  88. {
  89. if (document == null)
  90. throw new ArgumentNullException ("document");
  91. envdoc = document;
  92. }
  93. public SignedXml (XmlElement elem) : this ()
  94. {
  95. if (elem == null)
  96. throw new ArgumentNullException ("elem");
  97. envdoc = new XmlDocument ();
  98. envdoc.LoadXml (elem.OuterXml);
  99. }
  100. #if NET_2_0
  101. public EncryptedXml EncryptedXml {
  102. get { return encryptedXml; }
  103. set { encryptedXml = value; }
  104. }
  105. #endif
  106. public KeyInfo KeyInfo {
  107. get { return m_signature.KeyInfo; }
  108. set { m_signature.KeyInfo = value; }
  109. }
  110. public Signature Signature {
  111. get { return m_signature; }
  112. }
  113. public string SignatureLength {
  114. get { return m_signature.SignedInfo.SignatureLength; }
  115. }
  116. public string SignatureMethod {
  117. get { return m_signature.SignedInfo.SignatureMethod; }
  118. }
  119. public byte[] SignatureValue {
  120. get { return m_signature.SignatureValue; }
  121. }
  122. public SignedInfo SignedInfo {
  123. get { return m_signature.SignedInfo; }
  124. }
  125. public AsymmetricAlgorithm SigningKey {
  126. get { return key; }
  127. set { key = value; }
  128. }
  129. // NOTE: CryptoAPI related ? documented as fx internal
  130. public string SigningKeyName {
  131. get { return m_strSigningKeyName; }
  132. set { m_strSigningKeyName = value; }
  133. }
  134. public void AddObject (DataObject dataObject)
  135. {
  136. m_signature.AddObject (dataObject);
  137. }
  138. public void AddReference (Reference reference)
  139. {
  140. m_signature.SignedInfo.AddReference (reference);
  141. }
  142. private Stream ApplyTransform (Transform t, XmlDocument input)
  143. {
  144. // These transformer modify input document, which should
  145. // not affect to the input itself.
  146. if (t is XmlDsigXPathTransform ||
  147. t is XmlDsigEnvelopedSignatureTransform)
  148. input = (XmlDocument) input.Clone ();
  149. t.LoadInput (input);
  150. if (t is XmlDsigEnvelopedSignatureTransform)
  151. // It returns XmlDocument for XmlDocument input.
  152. return CanonicalizeOutput (t.GetOutput ());
  153. object obj = t.GetOutput ();
  154. if (obj is Stream)
  155. return (Stream) obj;
  156. else if (obj is XmlDocument) {
  157. MemoryStream ms = new MemoryStream ();
  158. XmlTextWriter xtw = new XmlTextWriter (ms, Encoding.UTF8);
  159. ((XmlDocument) obj).WriteTo (xtw);
  160. return ms;
  161. }
  162. else if (obj == null) {
  163. throw new NotImplementedException ("This should not occur. Transform is " + t + ".");
  164. }
  165. else {
  166. // e.g. XmlDsigXPathTransform returns XmlNodeList
  167. return CanonicalizeOutput (obj);
  168. }
  169. }
  170. private Stream CanonicalizeOutput (object obj)
  171. {
  172. Transform c14n = GetC14NMethod ();
  173. c14n.LoadInput (obj);
  174. return (Stream) c14n.GetOutput ();
  175. }
  176. private XmlDocument GetManifest (Reference r)
  177. {
  178. XmlDocument doc = new XmlDocument ();
  179. doc.PreserveWhitespace = true;
  180. if (r.Uri [0] == '#') {
  181. // local manifest
  182. if (signatureElement != null) {
  183. XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1));
  184. if (xel == null)
  185. throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1));
  186. doc.LoadXml (xel.OuterXml);
  187. FixupNamespaceNodes (xel, doc.DocumentElement);
  188. }
  189. }
  190. else if (xmlResolver != null) {
  191. // TODO: need testing
  192. Stream s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
  193. doc.Load (s);
  194. }
  195. if (doc.FirstChild != null) {
  196. // keep a copy of the manifests to check their references later
  197. if (manifests == null)
  198. manifests = new ArrayList ();
  199. manifests.Add (doc);
  200. return doc;
  201. }
  202. return null;
  203. }
  204. private void FixupNamespaceNodes (XmlElement src, XmlElement dst)
  205. {
  206. // add namespace nodes
  207. foreach (XmlAttribute attr in src.SelectNodes ("namespace::*")) {
  208. if (attr.LocalName == "xml")
  209. continue;
  210. if (attr.OwnerElement == src)
  211. continue;
  212. dst.SetAttributeNode (dst.OwnerDocument.ImportNode (attr, true) as XmlAttribute);
  213. }
  214. }
  215. [MonoTODO ("Need testing")]
  216. private byte[] GetReferenceHash (Reference r)
  217. {
  218. Stream s = null;
  219. XmlDocument doc = null;
  220. if (r.Uri == String.Empty) {
  221. doc = envdoc;
  222. }
  223. else if (r.Type == XmlSignature.Uri.Manifest) {
  224. doc = GetManifest (r);
  225. }
  226. else {
  227. doc = new XmlDocument ();
  228. doc.PreserveWhitespace = true;
  229. string objectName = null;
  230. if (r.Uri.StartsWith ("#xpointer")) {
  231. string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars));
  232. if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
  233. // FIXME: how to handle invalid xpointer?
  234. uri = String.Empty;
  235. else
  236. uri = uri.Substring (1, uri.Length - 2);
  237. if (uri == "/")
  238. doc = envdoc;
  239. else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')')
  240. // id('foo'), id("foo")
  241. objectName = uri.Substring (4, uri.Length - 6);
  242. }
  243. else if (r.Uri [0] == '#') {
  244. objectName = r.Uri.Substring (1);
  245. }
  246. else if (xmlResolver != null) {
  247. // TODO: test but doc says that Resolver = null -> no access
  248. try {
  249. // no way to know if valid without throwing an exception
  250. Uri uri = new Uri (r.Uri);
  251. s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
  252. }
  253. catch {
  254. // may still be a local file (and maybe not xml)
  255. s = File.OpenRead (r.Uri);
  256. }
  257. }
  258. if (objectName != null) {
  259. foreach (DataObject obj in m_signature.ObjectList) {
  260. if (obj.Id == objectName) {
  261. XmlElement xel = obj.GetXml ();
  262. doc.LoadXml (xel.OuterXml);
  263. FixupNamespaceNodes (xel, doc.DocumentElement);
  264. break;
  265. }
  266. }
  267. }
  268. }
  269. if (r.TransformChain.Count > 0) {
  270. foreach (Transform t in r.TransformChain) {
  271. if (s == null) {
  272. s = ApplyTransform (t, doc);
  273. }
  274. else {
  275. t.LoadInput (s);
  276. object o = t.GetOutput ();
  277. if (o is Stream)
  278. s = (Stream) o;
  279. else
  280. s = CanonicalizeOutput (o);
  281. }
  282. }
  283. }
  284. else if (s == null) {
  285. // we must not C14N references from outside the document
  286. // e.g. non-xml documents
  287. if (r.Uri [0] != '#') {
  288. s = new MemoryStream ();
  289. doc.Save (s);
  290. }
  291. else {
  292. // apply default C14N transformation
  293. s = ApplyTransform (new XmlDsigC14NTransform (), doc);
  294. }
  295. }
  296. HashAlgorithm digest = GetHash (r.DigestMethod);
  297. return digest.ComputeHash (s);
  298. }
  299. private void DigestReferences ()
  300. {
  301. // we must tell each reference which hash algorithm to use
  302. // before asking for the SignedInfo XML !
  303. foreach (Reference r in m_signature.SignedInfo.References) {
  304. // assume SHA-1 if nothing is specified
  305. if (r.DigestMethod == null)
  306. r.DigestMethod = XmlDsigSHA1Url;
  307. r.DigestValue = GetReferenceHash (r);
  308. }
  309. }
  310. private Transform GetC14NMethod ()
  311. {
  312. Transform t = (Transform) CryptoConfig.CreateFromName (m_signature.SignedInfo.CanonicalizationMethod);
  313. if (t == null)
  314. throw new CryptographicException ("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod);
  315. return t;
  316. }
  317. private Stream SignedInfoTransformed ()
  318. {
  319. Transform t = GetC14NMethod ();
  320. if (signatureElement == null) {
  321. // when creating signatures
  322. XmlDocument doc = new XmlDocument ();
  323. doc.PreserveWhitespace = true;
  324. doc.LoadXml (m_signature.SignedInfo.GetXml ().OuterXml);
  325. if (envdoc != null)
  326. foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes ("namespace::*")) {
  327. if (attr.LocalName == "xml")
  328. continue;
  329. if (attr.Prefix == doc.DocumentElement.Prefix)
  330. continue;
  331. doc.DocumentElement.SetAttributeNode (doc.ImportNode (attr, true) as XmlAttribute);
  332. }
  333. t.LoadInput (doc);
  334. }
  335. else {
  336. // when verifying signatures
  337. // TODO - check m_signature.SignedInfo.Id
  338. XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
  339. StringWriter sw = new StringWriter ();
  340. XmlTextWriter xtw = new XmlTextWriter (sw);
  341. xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI);
  342. // context namespace nodes (except for "xmlns:xml")
  343. XmlNodeList nl = el.SelectNodes ("namespace::*");
  344. foreach (XmlAttribute attr in nl) {
  345. if (attr.ParentNode == el)
  346. continue;
  347. if (attr.LocalName == "xml")
  348. continue;
  349. if (attr.Prefix == el.Prefix)
  350. continue;
  351. attr.WriteTo (xtw);
  352. }
  353. foreach (XmlNode attr in el.Attributes)
  354. attr.WriteTo (xtw);
  355. foreach (XmlNode n in el.ChildNodes)
  356. n.WriteTo (xtw);
  357. xtw.WriteEndElement ();
  358. byte [] si = Encoding.UTF8.GetBytes (sw.ToString ());
  359. MemoryStream ms = new MemoryStream ();
  360. ms.Write (si, 0, si.Length);
  361. ms.Position = 0;
  362. t.LoadInput (ms);
  363. }
  364. // C14N and C14NWithComments always return a Stream in GetOutput
  365. return (Stream) t.GetOutput ();
  366. }
  367. // reuse hash - most document will always use the same hash
  368. private HashAlgorithm GetHash (string algorithm)
  369. {
  370. HashAlgorithm hash = (HashAlgorithm) hashes [algorithm];
  371. if (hash == null) {
  372. hash = HashAlgorithm.Create (algorithm);
  373. if (hash == null)
  374. throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm);
  375. hashes.Add (algorithm, hash);
  376. // now ready to be used
  377. }
  378. else {
  379. // important before reusing an hash object
  380. hash.Initialize ();
  381. }
  382. return hash;
  383. }
  384. public bool CheckSignature ()
  385. {
  386. return (CheckSignatureInternal (null) != null);
  387. }
  388. private bool CheckReferenceIntegrity (ArrayList referenceList)
  389. {
  390. if (referenceList == null)
  391. return false;
  392. // check digest (hash) for every reference
  393. foreach (Reference r in referenceList) {
  394. // stop at first broken reference
  395. byte[] hash = GetReferenceHash (r);
  396. if (! Compare (r.DigestValue, hash))
  397. return false;
  398. }
  399. return true;
  400. }
  401. public bool CheckSignature (AsymmetricAlgorithm key)
  402. {
  403. if (key == null)
  404. throw new ArgumentNullException ("key");
  405. return (CheckSignatureInternal (key) != null);
  406. }
  407. private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
  408. {
  409. pkEnumerator = null;
  410. if (key != null) {
  411. // check with supplied key
  412. if (!CheckSignatureWithKey (key))
  413. return null;
  414. }
  415. else {
  416. if (Signature.KeyInfo == null)
  417. throw new CryptographicException ("At least one KeyInfo is required.");
  418. // no supplied key, iterates all KeyInfo
  419. while ((key = GetPublicKey ()) != null) {
  420. if (CheckSignatureWithKey (key)) {
  421. break;
  422. }
  423. }
  424. pkEnumerator = null;
  425. if (key == null)
  426. return null;
  427. }
  428. // some parts may need to be downloaded
  429. // so where doing it last
  430. if (!CheckReferenceIntegrity (m_signature.SignedInfo.References))
  431. return null;
  432. if (manifests != null) {
  433. // do not use foreach as a manifest could contain manifests...
  434. for (int i=0; i < manifests.Count; i++) {
  435. Manifest manifest = new Manifest ((manifests [i] as XmlDocument).DocumentElement);
  436. if (! CheckReferenceIntegrity (manifest.References))
  437. return null;
  438. }
  439. }
  440. return key;
  441. }
  442. // Is the signature (over SignedInfo) valid ?
  443. private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
  444. {
  445. if (key == null)
  446. return false;
  447. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
  448. if (sd == null)
  449. return false;
  450. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  451. if (verifier == null)
  452. return false;
  453. try {
  454. verifier.SetKey (key);
  455. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  456. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  457. // get the hash of the C14N SignedInfo element
  458. MemoryStream ms = (MemoryStream) SignedInfoTransformed ();
  459. byte[] digest = hash.ComputeHash (ms);
  460. return verifier.VerifySignature (digest, m_signature.SignatureValue);
  461. }
  462. catch {
  463. // e.g. SignatureMethod != AsymmetricAlgorithm type
  464. return false;
  465. }
  466. }
  467. private bool Compare (byte[] expected, byte[] actual)
  468. {
  469. bool result = ((expected != null) && (actual != null));
  470. if (result) {
  471. int l = expected.Length;
  472. result = (l == actual.Length);
  473. if (result) {
  474. for (int i=0; i < l; i++) {
  475. if (expected[i] != actual[i])
  476. return false;
  477. }
  478. }
  479. }
  480. return result;
  481. }
  482. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  483. {
  484. if (macAlg == null)
  485. throw new ArgumentNullException ("macAlg");
  486. pkEnumerator = null;
  487. // Is the signature (over SignedInfo) valid ?
  488. Stream s = SignedInfoTransformed ();
  489. if (s == null)
  490. return false;
  491. byte[] actual = macAlg.ComputeHash (s);
  492. // HMAC signature may be partial
  493. if (m_signature.SignedInfo.SignatureLength != null) {
  494. int length = actual.Length;
  495. try {
  496. // SignatureLength is in bits
  497. length = (Int32.Parse (m_signature.SignedInfo.SignatureLength) >> 3);
  498. }
  499. catch {
  500. }
  501. if (length != actual.Length) {
  502. byte[] trunked = new byte [length];
  503. Buffer.BlockCopy (actual, 0, trunked, 0, length);
  504. actual = trunked;
  505. }
  506. }
  507. if (Compare (m_signature.SignatureValue, actual)) {
  508. // some parts may need to be downloaded
  509. // so where doing it last
  510. return CheckReferenceIntegrity (m_signature.SignedInfo.References);
  511. }
  512. return false;
  513. }
  514. #if NET_2_0
  515. [MonoTODO]
  516. public bool CheckSignature (X509CertificateEx certificate, bool verifySignatureOnly)
  517. {
  518. throw new NotImplementedException ();
  519. }
  520. #endif
  521. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  522. {
  523. signingKey = CheckSignatureInternal (null);
  524. return (signingKey != null);
  525. }
  526. public void ComputeSignature ()
  527. {
  528. if (key != null) {
  529. // required before hashing
  530. m_signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  531. DigestReferences ();
  532. AsymmetricSignatureFormatter signer = null;
  533. // in need for a CryptoConfig factory
  534. if (key is DSA)
  535. signer = new DSASignatureFormatter (key);
  536. else if (key is RSA)
  537. signer = new RSAPKCS1SignatureFormatter (key);
  538. if (signer != null) {
  539. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
  540. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  541. // get the hash of the C14N SignedInfo element
  542. byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
  543. signer.SetHashAlgorithm ("SHA1");
  544. m_signature.SignatureValue = signer.CreateSignature (digest);
  545. }
  546. }
  547. }
  548. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  549. {
  550. if (macAlg == null)
  551. throw new ArgumentNullException ("macAlg");
  552. if (macAlg is HMACSHA1) {
  553. DigestReferences ();
  554. m_signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  555. m_signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  556. }
  557. else
  558. throw new CryptographicException ("unsupported algorithm");
  559. }
  560. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  561. {
  562. // this works only if there's a DTD or XSD available to define the ID
  563. XmlElement xel = document.GetElementById (idValue);
  564. if (xel == null) {
  565. // search an "undefined" ID
  566. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  567. }
  568. return xel;
  569. }
  570. // According to book ".NET Framework Security" this method
  571. // iterates all possible keys then return null
  572. protected virtual AsymmetricAlgorithm GetPublicKey ()
  573. {
  574. if (m_signature.KeyInfo == null)
  575. return null;
  576. if (pkEnumerator == null) {
  577. pkEnumerator = m_signature.KeyInfo.GetEnumerator ();
  578. }
  579. if (pkEnumerator.MoveNext ()) {
  580. AsymmetricAlgorithm key = null;
  581. KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
  582. if (kic is DSAKeyValue)
  583. key = DSA.Create ();
  584. else if (kic is RSAKeyValue)
  585. key = RSA.Create ();
  586. if (key != null) {
  587. key.FromXmlString (kic.GetXml ().InnerXml);
  588. return key;
  589. }
  590. }
  591. return null;
  592. }
  593. public XmlElement GetXml ()
  594. {
  595. return m_signature.GetXml ();
  596. }
  597. public void LoadXml (XmlElement value)
  598. {
  599. if (value == null)
  600. throw new ArgumentNullException ("value");
  601. signatureElement = value;
  602. m_signature.LoadXml (value);
  603. }
  604. #if NET_1_1
  605. [ComVisible (false)]
  606. public XmlResolver Resolver {
  607. set { xmlResolver = value; }
  608. }
  609. #endif
  610. }
  611. }