SignedXml.cs 21 KB

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