SignedXml.cs 21 KB

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