SignedXml.cs 23 KB

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