SignedXml.cs 23 KB

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