SignedXml.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  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. #if NET_2_0
  149. || t is XmlDecryptionTransform
  150. #endif
  151. )
  152. input = (XmlDocument) input.Clone ();
  153. t.LoadInput (input);
  154. if (t is XmlDsigEnvelopedSignatureTransform)
  155. // It returns XmlDocument for XmlDocument input.
  156. return CanonicalizeOutput (t.GetOutput ());
  157. object obj = t.GetOutput ();
  158. if (obj is Stream)
  159. return (Stream) obj;
  160. else if (obj is XmlDocument) {
  161. MemoryStream ms = new MemoryStream ();
  162. XmlTextWriter xtw = new XmlTextWriter (ms, Encoding.UTF8);
  163. ((XmlDocument) obj).WriteTo (xtw);
  164. xtw.Flush ();
  165. // Rewind to the start of the stream
  166. ms.Position = 0;
  167. return ms;
  168. }
  169. else if (obj == null) {
  170. throw new NotImplementedException ("This should not occur. Transform is " + t + ".");
  171. }
  172. else {
  173. // e.g. XmlDsigXPathTransform returns XmlNodeList
  174. return CanonicalizeOutput (obj);
  175. }
  176. }
  177. private Stream CanonicalizeOutput (object obj)
  178. {
  179. Transform c14n = GetC14NMethod ();
  180. c14n.LoadInput (obj);
  181. return (Stream) c14n.GetOutput ();
  182. }
  183. private XmlDocument GetManifest (Reference r)
  184. {
  185. XmlDocument doc = new XmlDocument ();
  186. doc.PreserveWhitespace = true;
  187. if (r.Uri [0] == '#') {
  188. // local manifest
  189. if (signatureElement != null) {
  190. XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1));
  191. if (xel == null)
  192. throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1));
  193. doc.LoadXml (xel.OuterXml);
  194. FixupNamespaceNodes (xel, doc.DocumentElement);
  195. }
  196. }
  197. else if (xmlResolver != null) {
  198. // TODO: need testing
  199. Stream s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
  200. doc.Load (s);
  201. }
  202. if (doc.FirstChild != null) {
  203. // keep a copy of the manifests to check their references later
  204. if (manifests == null)
  205. manifests = new ArrayList ();
  206. manifests.Add (doc);
  207. return doc;
  208. }
  209. return null;
  210. }
  211. private void FixupNamespaceNodes (XmlElement src, XmlElement dst)
  212. {
  213. // add namespace nodes
  214. foreach (XmlAttribute attr in src.SelectNodes ("namespace::*")) {
  215. if (attr.LocalName == "xml")
  216. continue;
  217. if (attr.OwnerElement == src)
  218. continue;
  219. dst.SetAttributeNode (dst.OwnerDocument.ImportNode (attr, true) as XmlAttribute);
  220. }
  221. }
  222. [MonoTODO ("Need testing")]
  223. private byte[] GetReferenceHash (Reference r)
  224. {
  225. Stream s = null;
  226. XmlDocument doc = null;
  227. if (r.Uri == String.Empty) {
  228. doc = envdoc;
  229. }
  230. else if (r.Type == XmlSignature.Uri.Manifest) {
  231. doc = GetManifest (r);
  232. }
  233. else {
  234. doc = new XmlDocument ();
  235. doc.PreserveWhitespace = true;
  236. string objectName = null;
  237. if (r.Uri.StartsWith ("#xpointer")) {
  238. string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars));
  239. if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
  240. // FIXME: how to handle invalid xpointer?
  241. uri = String.Empty;
  242. else
  243. uri = uri.Substring (1, uri.Length - 2);
  244. if (uri == "/")
  245. doc = envdoc;
  246. else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')')
  247. // id('foo'), id("foo")
  248. objectName = uri.Substring (4, uri.Length - 6);
  249. }
  250. else if (r.Uri [0] == '#') {
  251. objectName = r.Uri.Substring (1);
  252. }
  253. else if (xmlResolver != null) {
  254. // TODO: test but doc says that Resolver = null -> no access
  255. try {
  256. // no way to know if valid without throwing an exception
  257. Uri uri = new Uri (r.Uri);
  258. s = (Stream) xmlResolver.GetEntity (uri, null, typeof (Stream));
  259. }
  260. catch {
  261. // may still be a local file (and maybe not xml)
  262. s = File.OpenRead (r.Uri);
  263. }
  264. }
  265. if (objectName != null) {
  266. foreach (DataObject obj in m_signature.ObjectList) {
  267. if (obj.Id == objectName) {
  268. XmlElement xel = obj.GetXml ();
  269. doc.LoadXml (xel.OuterXml);
  270. FixupNamespaceNodes (xel, doc.DocumentElement);
  271. break;
  272. }
  273. }
  274. }
  275. }
  276. if (r.TransformChain.Count > 0) {
  277. foreach (Transform t in r.TransformChain) {
  278. if (s == null) {
  279. s = ApplyTransform (t, doc);
  280. }
  281. else {
  282. t.LoadInput (s);
  283. object o = t.GetOutput ();
  284. if (o is Stream)
  285. s = (Stream) o;
  286. else
  287. s = CanonicalizeOutput (o);
  288. }
  289. }
  290. }
  291. else if (s == null) {
  292. // we must not C14N references from outside the document
  293. // e.g. non-xml documents
  294. if (r.Uri [0] != '#') {
  295. s = new MemoryStream ();
  296. doc.Save (s);
  297. }
  298. else {
  299. // apply default C14N transformation
  300. s = ApplyTransform (new XmlDsigC14NTransform (), doc);
  301. }
  302. }
  303. HashAlgorithm digest = GetHash (r.DigestMethod);
  304. return digest.ComputeHash (s);
  305. }
  306. private void DigestReferences ()
  307. {
  308. // we must tell each reference which hash algorithm to use
  309. // before asking for the SignedInfo XML !
  310. foreach (Reference r in m_signature.SignedInfo.References) {
  311. // assume SHA-1 if nothing is specified
  312. if (r.DigestMethod == null)
  313. r.DigestMethod = XmlDsigSHA1Url;
  314. r.DigestValue = GetReferenceHash (r);
  315. }
  316. }
  317. private Transform GetC14NMethod ()
  318. {
  319. Transform t = (Transform) CryptoConfig.CreateFromName (m_signature.SignedInfo.CanonicalizationMethod);
  320. if (t == null)
  321. throw new CryptographicException ("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod);
  322. return t;
  323. }
  324. private Stream SignedInfoTransformed ()
  325. {
  326. Transform t = GetC14NMethod ();
  327. if (signatureElement == null) {
  328. // when creating signatures
  329. XmlDocument doc = new XmlDocument ();
  330. doc.PreserveWhitespace = true;
  331. doc.LoadXml (m_signature.SignedInfo.GetXml ().OuterXml);
  332. if (envdoc != null)
  333. foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes ("namespace::*")) {
  334. if (attr.LocalName == "xml")
  335. continue;
  336. if (attr.Prefix == doc.DocumentElement.Prefix)
  337. continue;
  338. doc.DocumentElement.SetAttributeNode (doc.ImportNode (attr, true) as XmlAttribute);
  339. }
  340. t.LoadInput (doc);
  341. }
  342. else {
  343. // when verifying signatures
  344. // TODO - check m_signature.SignedInfo.Id
  345. XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
  346. StringWriter sw = new StringWriter ();
  347. XmlTextWriter xtw = new XmlTextWriter (sw);
  348. xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI);
  349. // context namespace nodes (except for "xmlns:xml")
  350. XmlNodeList nl = el.SelectNodes ("namespace::*");
  351. foreach (XmlAttribute attr in nl) {
  352. if (attr.ParentNode == el)
  353. continue;
  354. if (attr.LocalName == "xml")
  355. continue;
  356. if (attr.Prefix == el.Prefix)
  357. continue;
  358. attr.WriteTo (xtw);
  359. }
  360. foreach (XmlNode attr in el.Attributes)
  361. attr.WriteTo (xtw);
  362. foreach (XmlNode n in el.ChildNodes)
  363. n.WriteTo (xtw);
  364. xtw.WriteEndElement ();
  365. byte [] si = Encoding.UTF8.GetBytes (sw.ToString ());
  366. MemoryStream ms = new MemoryStream ();
  367. ms.Write (si, 0, si.Length);
  368. ms.Position = 0;
  369. t.LoadInput (ms);
  370. }
  371. // C14N and C14NWithComments always return a Stream in GetOutput
  372. return (Stream) t.GetOutput ();
  373. }
  374. // reuse hash - most document will always use the same hash
  375. private HashAlgorithm GetHash (string algorithm)
  376. {
  377. HashAlgorithm hash = (HashAlgorithm) hashes [algorithm];
  378. if (hash == null) {
  379. hash = HashAlgorithm.Create (algorithm);
  380. if (hash == null)
  381. throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm);
  382. hashes.Add (algorithm, hash);
  383. // now ready to be used
  384. }
  385. else {
  386. // important before reusing an hash object
  387. hash.Initialize ();
  388. }
  389. return hash;
  390. }
  391. public bool CheckSignature ()
  392. {
  393. return (CheckSignatureInternal (null) != null);
  394. }
  395. private bool CheckReferenceIntegrity (ArrayList referenceList)
  396. {
  397. if (referenceList == null)
  398. return false;
  399. // check digest (hash) for every reference
  400. foreach (Reference r in referenceList) {
  401. // stop at first broken reference
  402. byte[] hash = GetReferenceHash (r);
  403. if (! Compare (r.DigestValue, hash))
  404. return false;
  405. }
  406. return true;
  407. }
  408. public bool CheckSignature (AsymmetricAlgorithm key)
  409. {
  410. if (key == null)
  411. throw new ArgumentNullException ("key");
  412. return (CheckSignatureInternal (key) != null);
  413. }
  414. private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
  415. {
  416. pkEnumerator = null;
  417. if (key != null) {
  418. // check with supplied key
  419. if (!CheckSignatureWithKey (key))
  420. return null;
  421. }
  422. else {
  423. if (Signature.KeyInfo == null)
  424. throw new CryptographicException ("At least one KeyInfo is required.");
  425. // no supplied key, iterates all KeyInfo
  426. while ((key = GetPublicKey ()) != null) {
  427. if (CheckSignatureWithKey (key)) {
  428. break;
  429. }
  430. }
  431. pkEnumerator = null;
  432. if (key == null)
  433. return null;
  434. }
  435. // some parts may need to be downloaded
  436. // so where doing it last
  437. if (!CheckReferenceIntegrity (m_signature.SignedInfo.References))
  438. return null;
  439. if (manifests != null) {
  440. // do not use foreach as a manifest could contain manifests...
  441. for (int i=0; i < manifests.Count; i++) {
  442. Manifest manifest = new Manifest ((manifests [i] as XmlDocument).DocumentElement);
  443. if (! CheckReferenceIntegrity (manifest.References))
  444. return null;
  445. }
  446. }
  447. return key;
  448. }
  449. // Is the signature (over SignedInfo) valid ?
  450. private bool CheckSignatureWithKey (AsymmetricAlgorithm key)
  451. {
  452. if (key == null)
  453. return false;
  454. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
  455. if (sd == null)
  456. return false;
  457. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  458. if (verifier == null)
  459. return false;
  460. try {
  461. verifier.SetKey (key);
  462. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  463. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  464. // get the hash of the C14N SignedInfo element
  465. MemoryStream ms = (MemoryStream) SignedInfoTransformed ();
  466. byte[] digest = hash.ComputeHash (ms);
  467. return verifier.VerifySignature (digest, m_signature.SignatureValue);
  468. }
  469. catch {
  470. // e.g. SignatureMethod != AsymmetricAlgorithm type
  471. return false;
  472. }
  473. }
  474. private bool Compare (byte[] expected, byte[] actual)
  475. {
  476. bool result = ((expected != null) && (actual != null));
  477. if (result) {
  478. int l = expected.Length;
  479. result = (l == actual.Length);
  480. if (result) {
  481. for (int i=0; i < l; i++) {
  482. if (expected[i] != actual[i])
  483. return false;
  484. }
  485. }
  486. }
  487. return result;
  488. }
  489. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  490. {
  491. if (macAlg == null)
  492. throw new ArgumentNullException ("macAlg");
  493. pkEnumerator = null;
  494. // Is the signature (over SignedInfo) valid ?
  495. Stream s = SignedInfoTransformed ();
  496. if (s == null)
  497. return false;
  498. byte[] actual = macAlg.ComputeHash (s);
  499. // HMAC signature may be partial
  500. if (m_signature.SignedInfo.SignatureLength != null) {
  501. int length = actual.Length;
  502. try {
  503. // SignatureLength is in bits
  504. length = (Int32.Parse (m_signature.SignedInfo.SignatureLength) >> 3);
  505. }
  506. catch {
  507. }
  508. if (length != actual.Length) {
  509. byte[] trunked = new byte [length];
  510. Buffer.BlockCopy (actual, 0, trunked, 0, length);
  511. actual = trunked;
  512. }
  513. }
  514. if (Compare (m_signature.SignatureValue, actual)) {
  515. // some parts may need to be downloaded
  516. // so where doing it last
  517. return CheckReferenceIntegrity (m_signature.SignedInfo.References);
  518. }
  519. return false;
  520. }
  521. #if NET_2_0
  522. [MonoTODO]
  523. public bool CheckSignature (X509CertificateEx certificate, bool verifySignatureOnly)
  524. {
  525. throw new NotImplementedException ();
  526. }
  527. #endif
  528. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  529. {
  530. signingKey = CheckSignatureInternal (null);
  531. return (signingKey != null);
  532. }
  533. public void ComputeSignature ()
  534. {
  535. if (key != null) {
  536. // required before hashing
  537. m_signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  538. DigestReferences ();
  539. AsymmetricSignatureFormatter signer = null;
  540. // in need for a CryptoConfig factory
  541. if (key is DSA)
  542. signer = new DSASignatureFormatter (key);
  543. else if (key is RSA)
  544. signer = new RSAPKCS1SignatureFormatter (key);
  545. if (signer != null) {
  546. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
  547. HashAlgorithm hash = GetHash (sd.DigestAlgorithm);
  548. // get the hash of the C14N SignedInfo element
  549. byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
  550. signer.SetHashAlgorithm ("SHA1");
  551. m_signature.SignatureValue = signer.CreateSignature (digest);
  552. }
  553. }
  554. }
  555. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  556. {
  557. if (macAlg == null)
  558. throw new ArgumentNullException ("macAlg");
  559. if (macAlg is HMACSHA1) {
  560. DigestReferences ();
  561. m_signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  562. m_signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  563. }
  564. else
  565. throw new CryptographicException ("unsupported algorithm");
  566. }
  567. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  568. {
  569. // this works only if there's a DTD or XSD available to define the ID
  570. XmlElement xel = document.GetElementById (idValue);
  571. if (xel == null) {
  572. // search an "undefined" ID
  573. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  574. }
  575. return xel;
  576. }
  577. // According to book ".NET Framework Security" this method
  578. // iterates all possible keys then return null
  579. protected virtual AsymmetricAlgorithm GetPublicKey ()
  580. {
  581. if (m_signature.KeyInfo == null)
  582. return null;
  583. if (pkEnumerator == null) {
  584. pkEnumerator = m_signature.KeyInfo.GetEnumerator ();
  585. }
  586. if (pkEnumerator.MoveNext ()) {
  587. AsymmetricAlgorithm key = null;
  588. KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
  589. if (kic is DSAKeyValue)
  590. key = DSA.Create ();
  591. else if (kic is RSAKeyValue)
  592. key = RSA.Create ();
  593. if (key != null) {
  594. key.FromXmlString (kic.GetXml ().InnerXml);
  595. return key;
  596. }
  597. }
  598. return null;
  599. }
  600. public XmlElement GetXml ()
  601. {
  602. return m_signature.GetXml (envdoc);
  603. }
  604. public void LoadXml (XmlElement value)
  605. {
  606. if (value == null)
  607. throw new ArgumentNullException ("value");
  608. signatureElement = value;
  609. m_signature.LoadXml (value);
  610. #if NET_2_0
  611. // Need to give the EncryptedXml object to the
  612. // XmlDecryptionTransform to give it a fighting
  613. // chance at decrypting the document.
  614. foreach (Reference r in m_signature.SignedInfo.References) {
  615. foreach (Transform t in r.TransformChain) {
  616. if (t is XmlDecryptionTransform)
  617. ((XmlDecryptionTransform) t).EncryptedXml = EncryptedXml;
  618. }
  619. }
  620. #endif
  621. }
  622. #if NET_1_1
  623. [ComVisible (false)]
  624. public XmlResolver Resolver {
  625. set { xmlResolver = value; }
  626. }
  627. #endif
  628. }
  629. }