05c2b091d98b229262f43bc1c25577656f0009a2
[mono.git] / mcs / class / System.Security / System.Security.Cryptography.Xml / SignedXml.cs
1 //
2 // SignedXml.cs - SignedXml implementation for XML Signature
3 //
4 // Author:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //      Atsushi Enomoto <atsushi@ximian.com>
7 //      Tim Coleman <tim@timcoleman.com>
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
33 using System.Collections;
34 using System.IO;
35 using System.Runtime.InteropServices;
36 using System.Security.Cryptography;
37 using System.Security.Policy;
38 using System.Net;
39 using System.Text;
40 using System.Xml;
41 using System.Security.Cryptography.X509Certificates;
42
43 namespace System.Security.Cryptography.Xml {
44
45         public class SignedXml {
46
47                 public const string XmlDsigCanonicalizationUrl                  = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
48                 public const string XmlDsigCanonicalizationWithCommentsUrl      = XmlDsigCanonicalizationUrl + "#WithComments";
49                 public const string XmlDsigDSAUrl                               = XmlDsigNamespaceUrl + "dsa-sha1";
50                 public const string XmlDsigHMACSHA1Url                          = XmlDsigNamespaceUrl + "hmac-sha1";
51                 public const string XmlDsigMinimalCanonicalizationUrl           = XmlDsigNamespaceUrl + "minimal";
52                 public const string XmlDsigNamespaceUrl                         = "http://www.w3.org/2000/09/xmldsig#";
53                 public const string XmlDsigRSASHA1Url                           = XmlDsigNamespaceUrl + "rsa-sha1";
54                 public const string XmlDsigSHA1Url                              = XmlDsigNamespaceUrl + "sha1";
55
56                 public const string XmlDecryptionTransformUrl                   = "http://www.w3.org/2002/07/decrypt#XML";
57                 public const string XmlDsigBase64TransformUrl                   = XmlDsigNamespaceUrl + "base64";
58                 public const string XmlDsigC14NTransformUrl                     = XmlDsigCanonicalizationUrl;
59                 public const string XmlDsigC14NWithCommentsTransformUrl         = XmlDsigCanonicalizationWithCommentsUrl;
60                 public const string XmlDsigEnvelopedSignatureTransformUrl       = XmlDsigNamespaceUrl + "enveloped-signature";
61                 public const string XmlDsigExcC14NTransformUrl                  = "http://www.w3.org/2001/10/xml-exc-c14n#";
62                 public const string XmlDsigExcC14NWithCommentsTransformUrl      = XmlDsigExcC14NTransformUrl + "WithComments";
63                 public const string XmlDsigXPathTransformUrl                    = "http://www.w3.org/TR/1999/REC-xpath-19991116";
64                 public const string XmlDsigXsltTransformUrl                     = "http://www.w3.org/TR/1999/REC-xslt-19991116";
65                 public const string XmlLicenseTransformUrl                      = "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform";
66
67                 private EncryptedXml encryptedXml;
68
69                 protected Signature m_signature;
70                 private AsymmetricAlgorithm key;
71                 protected string m_strSigningKeyName;
72                 private XmlDocument envdoc;
73                 private IEnumerator pkEnumerator;
74                 private XmlElement signatureElement;
75                 private Hashtable hashes;
76                 // FIXME: enable it after CAS implementation
77                 private XmlResolver xmlResolver = new XmlUrlResolver ();
78                 private ArrayList manifests;
79                 private IEnumerator _x509Enumerator;
80
81                 private static readonly char [] whitespaceChars = new char [] {' ', '\r', '\n', '\t'};
82
83                 public SignedXml () 
84                 {
85                         m_signature = new Signature ();
86                         m_signature.SignedInfo = new SignedInfo ();
87                         hashes = new Hashtable (2); // 98% SHA1 for now
88                 }
89
90                 public SignedXml (XmlDocument document) : this ()
91                 {
92                         if (document == null)
93                                 throw new ArgumentNullException ("document");
94                         envdoc = document;
95                 }
96
97                 public SignedXml (XmlElement elem) : this ()
98                 {
99                         if (elem == null)
100                                 throw new ArgumentNullException ("elem");
101                         envdoc = new XmlDocument ();
102                         envdoc.LoadXml (elem.OuterXml);
103                 }
104
105                 [ComVisible (false)]
106                 public EncryptedXml EncryptedXml {
107                         get { return encryptedXml; }
108                         set { encryptedXml = value; }
109                 }
110
111                 public KeyInfo KeyInfo {
112                         get {
113                                 if (m_signature.KeyInfo == null)
114                                         m_signature.KeyInfo = new KeyInfo ();
115                                 return m_signature.KeyInfo;
116                         }
117                         set { m_signature.KeyInfo = value; }
118                 }
119
120                 public Signature Signature {
121                         get { return m_signature; }
122                 }
123
124                 public string SignatureLength {
125                         get { return m_signature.SignedInfo.SignatureLength; }
126                 }
127
128                 public string SignatureMethod {
129                         get { return m_signature.SignedInfo.SignatureMethod; }
130                 }
131
132                 public byte[] SignatureValue {
133                         get { return m_signature.SignatureValue; }
134                 }
135
136                 public SignedInfo SignedInfo {
137                         get { return m_signature.SignedInfo; }
138                 }
139
140                 public AsymmetricAlgorithm SigningKey {
141                         get { return key; }
142                         set { key = value; }
143                 }
144
145                 // NOTE: CryptoAPI related ? documented as fx internal
146                 public string SigningKeyName {
147                         get { return m_strSigningKeyName; }
148                         set { m_strSigningKeyName = value; }
149                 }
150
151                 public void AddObject (DataObject dataObject) 
152                 {
153                         m_signature.AddObject (dataObject);
154                 }
155
156                 public void AddReference (Reference reference) 
157                 {
158                         if (reference == null)
159                                 throw new ArgumentNullException ("reference");
160                         m_signature.SignedInfo.AddReference (reference);
161                 }
162
163                 private Stream ApplyTransform (Transform t, XmlDocument input) 
164                 {
165                         // These transformer modify input document, which should
166                         // not affect to the input itself.
167                         if (t is XmlDsigXPathTransform 
168                                 || t is XmlDsigEnvelopedSignatureTransform
169                                 || t is XmlDecryptionTransform
170                         )
171                                 input = (XmlDocument) input.Clone ();
172
173                         t.LoadInput (input);
174
175                         if (t is XmlDsigEnvelopedSignatureTransform)
176                                 // It returns XmlDocument for XmlDocument input.
177                                 return CanonicalizeOutput (t.GetOutput ());
178
179                         object obj = t.GetOutput ();
180                         if (obj is Stream)
181                                 return (Stream) obj;
182                         else if (obj is XmlDocument) {
183                                 MemoryStream ms = new MemoryStream ();
184                                 XmlTextWriter xtw = new XmlTextWriter (ms, Encoding.UTF8);
185                                 ((XmlDocument) obj).WriteTo (xtw);
186
187                                 xtw.Flush ();
188
189                                 // Rewind to the start of the stream
190                                 ms.Position = 0;
191                                 return ms;
192                         }
193                         else if (obj == null) {
194                                 throw new NotImplementedException ("This should not occur. Transform is " + t + ".");
195                         }
196                         else {
197                                 // e.g. XmlDsigXPathTransform returns XmlNodeList
198                                 return CanonicalizeOutput (obj);
199                         }
200                 }
201
202                 private Stream CanonicalizeOutput (object obj)
203                 {
204                         Transform c14n = GetC14NMethod ();
205                         c14n.LoadInput (obj);
206                         return (Stream) c14n.GetOutput ();
207                 }
208
209                 private XmlDocument GetManifest (Reference r) 
210                 {
211                         XmlDocument doc = new XmlDocument ();
212                         doc.PreserveWhitespace = true;
213
214                         if (r.Uri [0] == '#') {
215                                 // local manifest
216                                 if (signatureElement != null) {
217                                         XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1));
218                                         if (xel == null)
219                                                 throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1));
220                                         doc.AppendChild (doc.ImportNode (xel, true));
221                                         FixupNamespaceNodes (xel, doc.DocumentElement, false);
222                                 }
223                         }
224                         else if (xmlResolver != null) {
225                                 // TODO: need testing
226                                 Stream s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream));
227                                 doc.Load (s);
228                         }
229
230                         if (doc.FirstChild != null) {
231                                 // keep a copy of the manifests to check their references later
232                                 if (manifests == null)
233                                         manifests = new ArrayList ();
234                                 manifests.Add (doc);
235
236                                 return doc;
237                         }
238                         return null;
239                 }
240
241                 private void FixupNamespaceNodes (XmlElement src, XmlElement dst, bool ignoreDefault)
242                 {
243                         // add namespace nodes
244                         foreach (XmlAttribute attr in src.SelectNodes ("namespace::*")) {
245                                 if (attr.LocalName == "xml")
246                                         continue;
247                                 if (ignoreDefault && attr.LocalName == "xmlns")
248                                         continue;
249                                 dst.SetAttributeNode (dst.OwnerDocument.ImportNode (attr, true) as XmlAttribute);
250                         }
251                 }
252
253                 private byte[] GetReferenceHash (Reference r, bool check_hmac) 
254                 {
255                         Stream s = null;
256                         XmlDocument doc = null;
257                         if (r.Uri == String.Empty) {
258                                 doc = envdoc;
259                         }
260                         else if (r.Type == XmlSignature.Uri.Manifest) {
261                                 doc = GetManifest (r);
262                         }
263                         else {
264                                 doc = new XmlDocument ();
265                                 doc.PreserveWhitespace = true;
266                                 string objectName = null;
267
268                                 if (r.Uri.StartsWith ("#xpointer")) {
269                                         string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars));
270                                         if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')')
271                                                 // FIXME: how to handle invalid xpointer?
272                                                 uri = String.Empty;
273                                         else
274                                                 uri = uri.Substring (1, uri.Length - 2);
275                                         if (uri == "/")
276                                                 doc = envdoc;
277                                         else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')')
278                                                 // id('foo'), id("foo")
279                                                 objectName = uri.Substring (4, uri.Length - 6);
280                                 }
281                                 else if (r.Uri [0] == '#') {
282                                         objectName = r.Uri.Substring (1);
283                                 }
284                                 else if (xmlResolver != null) {
285                                         // TODO: test but doc says that Resolver = null -> no access
286                                         try {
287                                                 // no way to know if valid without throwing an exception
288                                                 Uri uri = new Uri (r.Uri);
289                                                 s = (Stream) xmlResolver.GetEntity (uri, null, typeof (Stream));
290                                         }
291                                         catch {
292                                                 // may still be a local file (and maybe not xml)
293                                                 s = File.OpenRead (r.Uri);
294                                         }
295                                 }
296                                 if (objectName != null) {
297                                         XmlElement found = null;
298                                         foreach (DataObject obj in m_signature.ObjectList) {
299                                                 if (obj.Id == objectName) {
300                                                         found = obj.GetXml ();
301                                                         found.SetAttribute ("xmlns", SignedXml.XmlDsigNamespaceUrl);
302                                                         doc.AppendChild (doc.ImportNode (found, true));
303                                                         // FIXME: there should be theoretical justification of copying namespace declaration nodes this way.
304                                                         foreach (XmlNode n in found.ChildNodes)
305                                                                 // Do not copy default namespace as it must be xmldsig namespace for "Object" element.
306                                                                 if (n.NodeType == XmlNodeType.Element)
307                                                                         FixupNamespaceNodes (n as XmlElement, doc.DocumentElement, true);
308                                                         break;
309                                                 }
310                                         }
311                                         if (found == null && envdoc != null) {
312                                                 found = GetIdElement (envdoc, objectName);
313                                                 if (found != null) {
314                                                         doc.AppendChild (doc.ImportNode (found, true));
315                                                         FixupNamespaceNodes (found, doc.DocumentElement, false);
316                                                 }
317                                         }
318                                         if (found == null)
319                                                 throw new CryptographicException (String.Format ("Malformed reference object: {0}", objectName));
320                                 }
321                         }
322
323                         if (r.TransformChain.Count > 0) {               
324                                 foreach (Transform t in r.TransformChain) {
325                                         if (s == null) {
326                                                 s = ApplyTransform (t, doc);
327                                         }
328                                         else {
329                                                 t.LoadInput (s);
330                                                 object o = t.GetOutput ();
331                                                 if (o is Stream)
332                                                         s = (Stream) o;
333                                                 else
334                                                         s = CanonicalizeOutput (o);
335                                         }
336                                 }
337                         }
338                         else if (s == null) {
339                                 // we must not C14N references from outside the document
340                                 // e.g. non-xml documents
341                                 if (r.Uri [0] != '#') {
342                                         s = new MemoryStream ();
343                                         doc.Save (s);
344                                 }
345                                 else {
346                                         // apply default C14N transformation
347                                         s = ApplyTransform (new XmlDsigC14NTransform (), doc);
348                                 }
349                         }
350                         HashAlgorithm digest = GetHash (r.DigestMethod, check_hmac);
351                         return (digest == null) ? null : digest.ComputeHash (s);
352                 }
353
354                 private void DigestReferences () 
355                 {
356                         // we must tell each reference which hash algorithm to use 
357                         // before asking for the SignedInfo XML !
358                         foreach (Reference r in m_signature.SignedInfo.References) {
359                                 // assume SHA-1 if nothing is specified
360                                 if (r.DigestMethod == null)
361                                         r.DigestMethod = XmlDsigSHA1Url;
362                                 r.DigestValue = GetReferenceHash (r, false);
363                         }
364                 }
365
366                 private Transform GetC14NMethod ()
367                 {
368                         Transform t = (Transform) CryptoConfig.CreateFromName (m_signature.SignedInfo.CanonicalizationMethod);
369                         if (t == null)
370                                 throw new CryptographicException ("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod);
371                         return t;
372                 }
373
374                 private Stream SignedInfoTransformed () 
375                 {
376                         Transform t = GetC14NMethod ();
377
378                         if (signatureElement == null) {
379                                 // when creating signatures
380                                 XmlDocument doc = new XmlDocument ();
381                                 doc.PreserveWhitespace = true;
382                                 doc.LoadXml (m_signature.SignedInfo.GetXml ().OuterXml);
383                                 if (envdoc != null)
384                                 foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes ("namespace::*")) {
385                                         if (attr.LocalName == "xml")
386                                                 continue;
387                                         if (attr.Prefix == doc.DocumentElement.Prefix)
388                                                 continue;
389                                         doc.DocumentElement.SetAttributeNode (doc.ImportNode (attr, true) as XmlAttribute);
390                                 }
391                                 t.LoadInput (doc);
392                         }
393                         else {
394                                 // when verifying signatures
395                                 // TODO - check m_signature.SignedInfo.Id
396                                 XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement;
397                                 StringWriter sw = new StringWriter ();
398                                 XmlTextWriter xtw = new XmlTextWriter (sw);
399                                 xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI);
400
401                                 // context namespace nodes (except for "xmlns:xml")
402                                 XmlNodeList nl = el.SelectNodes ("namespace::*");
403                                 foreach (XmlAttribute attr in nl) {
404                                         if (attr.ParentNode == el)
405                                                 continue;
406                                         if (attr.LocalName == "xml")
407                                                 continue;
408                                         if (attr.Prefix == el.Prefix)
409                                                 continue;
410                                         attr.WriteTo (xtw);
411                                 }
412                                 foreach (XmlNode attr in el.Attributes)
413                                         attr.WriteTo (xtw);
414                                 foreach (XmlNode n in el.ChildNodes)
415                                         n.WriteTo (xtw);
416
417                                 xtw.WriteEndElement ();
418                                 byte [] si = Encoding.UTF8.GetBytes (sw.ToString ());
419
420                                 MemoryStream ms = new MemoryStream ();
421                                 ms.Write (si, 0, si.Length);
422                                 ms.Position = 0;
423
424                                 t.LoadInput (ms);
425                         }
426                         // C14N and C14NWithComments always return a Stream in GetOutput
427                         return (Stream) t.GetOutput ();
428                 }
429
430                 // reuse hash - most document will always use the same hash
431                 private HashAlgorithm GetHash (string algorithm, bool check_hmac) 
432                 {
433                         HashAlgorithm hash = (HashAlgorithm) hashes [algorithm];
434                         if (hash == null) {
435                                 hash = HashAlgorithm.Create (algorithm);
436                                 if (hash == null)
437                                         throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm);
438                                 hashes.Add (algorithm, hash);
439                                 // now ready to be used
440                         }
441                         else {
442                                 // important before reusing an hash object
443                                 hash.Initialize ();
444                         }
445                         // we can sign using any hash algorith, including HMAC, but we can only verify hash (MS compatibility)
446                         if (check_hmac && (hash is KeyedHashAlgorithm))
447                                 return null;
448                         return hash;
449                 }
450
451                 public bool CheckSignature () 
452                 {
453                         return (CheckSignatureInternal (null) != null);
454                 }
455
456                 private bool CheckReferenceIntegrity (ArrayList referenceList) 
457                 {
458                         if (referenceList == null)
459                                 return false;
460
461                         // check digest (hash) for every reference
462                         foreach (Reference r in referenceList) {
463                                 // stop at first broken reference
464                                 byte[] hash = GetReferenceHash (r, true);
465                                 if (! Compare (r.DigestValue, hash))
466                                         return false;
467                         }
468                         return true;
469                 }
470
471                 public bool CheckSignature (AsymmetricAlgorithm key) 
472                 {
473                         if (key == null)
474                                 throw new ArgumentNullException ("key");
475                         return (CheckSignatureInternal (key) != null);
476                 }
477
478                 private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key)
479                 {
480                         pkEnumerator = null;
481
482                         if (key != null) {
483                                 // check with supplied key
484                                 if (!CheckSignatureWithKey (key))
485                                         return null;
486                         } else {
487                                 if (Signature.KeyInfo == null)
488                                         return null;
489                                 // no supplied key, iterates all KeyInfo
490                                 while ((key = GetPublicKey ()) != null) {
491                                         if (CheckSignatureWithKey (key)) {
492                                                 break;
493                                         }
494                                 }
495                                 pkEnumerator = null;
496                                 if (key == null)
497                                         return null;
498                         }
499
500                         // some parts may need to be downloaded
501                         // so where doing it last
502                         if (!CheckReferenceIntegrity (m_signature.SignedInfo.References))
503                                 return null;
504
505                         if (manifests != null) {
506                                 // do not use foreach as a manifest could contain manifests...
507                                 for (int i=0; i < manifests.Count; i++) {
508                                         Manifest manifest = new Manifest ((manifests [i] as XmlDocument).DocumentElement);
509                                         if (! CheckReferenceIntegrity (manifest.References))
510                                                 return null;
511                                 }
512                         }
513                         return key;
514                 }
515
516                 // Is the signature (over SignedInfo) valid ?
517                 private bool CheckSignatureWithKey (AsymmetricAlgorithm key) 
518                 {
519                         if (key == null)
520                                 return false;
521
522                         SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
523                         if (sd == null)
524                                 return false;
525
526                         AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
527                         if (verifier == null)
528                                 return false;
529
530                         try {
531                                 verifier.SetKey (key);
532                                 verifier.SetHashAlgorithm (sd.DigestAlgorithm);
533
534                                 HashAlgorithm hash = GetHash (sd.DigestAlgorithm, true);
535                                 // get the hash of the C14N SignedInfo element
536                                 MemoryStream ms = (MemoryStream) SignedInfoTransformed ();
537
538                                 byte[] digest = hash.ComputeHash (ms);
539                                 return verifier.VerifySignature (digest, m_signature.SignatureValue);
540                         }
541                         catch {
542                                 // e.g. SignatureMethod != AsymmetricAlgorithm type
543                                 return false;
544                         } 
545                 }
546
547                 private bool Compare (byte[] expected, byte[] actual) 
548                 {
549                         bool result = ((expected != null) && (actual != null));
550                         if (result) {
551                                 int l = expected.Length;
552                                 result = (l == actual.Length);
553                                 if (result) {
554                                         for (int i=0; i < l; i++) {
555                                                 if (expected[i] != actual[i])
556                                                         return false;
557                                         }
558                                 }
559                         }
560                         return result;
561                 }
562
563                 public bool CheckSignature (KeyedHashAlgorithm macAlg) 
564                 {
565                         if (macAlg == null)
566                                 throw new ArgumentNullException ("macAlg");
567
568                         pkEnumerator = null;
569
570                         // Is the signature (over SignedInfo) valid ?
571                         Stream s = SignedInfoTransformed ();
572                         if (s == null)
573                                 return false;
574
575                         byte[] actual = macAlg.ComputeHash (s);
576                         // HMAC signature may be partial and specified by <HMACOutputLength>
577                         if (m_signature.SignedInfo.SignatureLength != null) {
578                                 int length = Int32.Parse (m_signature.SignedInfo.SignatureLength);
579                                 // we only support signatures with a multiple of 8 bits
580                                 // and the value must match the signature length
581                                 if ((length & 7) != 0)
582                                         throw new CryptographicException ("Signature length must be a multiple of 8 bits.");
583
584                                 // SignatureLength is in bits (and we works on bytes, only in multiple of 8 bits)
585                                 // and both values must match for a signature to be valid
586                                 length >>= 3;
587                                 if (length != m_signature.SignatureValue.Length)
588                                         throw new CryptographicException ("Invalid signature length.");
589
590                                 // is the length "big" enough to make the signature meaningful ? 
591                                 // we use a minimum of 80 bits (10 bytes) or half the HMAC normal output length
592                                 // e.g. HMACMD5 output 128 bits but our minimum is 80 bits (not 64 bits)
593                                 int minimum = Math.Max (10, actual.Length / 2);
594                                 if (length < minimum)
595                                         throw new CryptographicException ("HMAC signature is too small");
596
597                                 if (length < actual.Length) {
598                                         byte[] trunked = new byte [length];
599                                         Buffer.BlockCopy (actual, 0, trunked, 0, length);
600                                         actual = trunked;
601                                 }
602                         }
603
604                         if (Compare (m_signature.SignatureValue, actual)) {
605                                 // some parts may need to be downloaded
606                                 // so where doing it last
607                                 return CheckReferenceIntegrity (m_signature.SignedInfo.References);
608                         }
609                         return false;
610                 }
611
612                 [MonoTODO]
613                 [ComVisible (false)]
614                 public bool CheckSignature (X509Certificate2 certificate, bool verifySignatureOnly)
615                 {
616                         throw new NotImplementedException ();
617                 }
618
619                 public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey) 
620                 {
621                         signingKey = CheckSignatureInternal (null);
622                         return (signingKey != null);
623                 }
624
625                 public void ComputeSignature () 
626                 {
627                         if (key != null) {
628                                 if (m_signature.SignedInfo.SignatureMethod == null)
629                                         // required before hashing
630                                         m_signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
631                                 else if (m_signature.SignedInfo.SignatureMethod != key.SignatureAlgorithm)
632                                         throw new CryptographicException ("Specified SignatureAlgorithm is not supported by the signing key.");
633                                 DigestReferences ();
634
635                                 AsymmetricSignatureFormatter signer = null;
636                                 // in need for a CryptoConfig factory
637                                 if (key is DSA)
638                                         signer = new DSASignatureFormatter (key);
639                                 else if (key is RSA) 
640                                         signer = new RSAPKCS1SignatureFormatter (key);
641
642                                 if (signer != null) {
643                                         SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod);
644
645                                         HashAlgorithm hash = GetHash (sd.DigestAlgorithm, false);
646                                         // get the hash of the C14N SignedInfo element
647                                         byte[] digest = hash.ComputeHash (SignedInfoTransformed ());
648
649                                         signer.SetHashAlgorithm ("SHA1");
650                                         m_signature.SignatureValue = signer.CreateSignature (digest);
651                                 }
652                         }
653                         else
654                                 throw new CryptographicException ("signing key is not specified");
655                 }
656
657                 public void ComputeSignature (KeyedHashAlgorithm macAlg) 
658                 {
659                         if (macAlg == null)
660                                 throw new ArgumentNullException ("macAlg");
661
662                         string method = null;
663
664                         if (macAlg is HMACSHA1) {
665                                 method = XmlDsigHMACSHA1Url;
666                         } else if (macAlg is HMACSHA256) {
667                                 method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
668                         } else if (macAlg is HMACSHA384) {
669                                 method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384";
670                         } else if (macAlg is HMACSHA512) {
671                                 method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512";
672                         } else if (macAlg is HMACRIPEMD160) {
673                                 method = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160";
674                         }
675
676                         if (method == null)
677                                 throw new CryptographicException ("unsupported algorithm");
678
679                         DigestReferences ();
680                         m_signature.SignedInfo.SignatureMethod = method;
681                         m_signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
682                 }
683
684                 public virtual XmlElement GetIdElement (XmlDocument document, string idValue) 
685                 {
686                         if ((document == null) || (idValue == null))
687                                 return null;
688
689                         // this works only if there's a DTD or XSD available to define the ID
690                         XmlElement xel = document.GetElementById (idValue);
691                         if (xel == null) {
692                                 // search an "undefined" ID
693                                 xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
694                                 if (xel == null) {
695                                         xel = (XmlElement) document.SelectSingleNode ("//*[@ID='" + idValue + "']");
696                                         if (xel == null) {
697                                                 xel = (XmlElement) document.SelectSingleNode ("//*[@id='" + idValue + "']");
698                                         }
699                                 }
700                         }
701                         return xel;
702                 }
703
704                 // According to book ".NET Framework Security" this method
705                 // iterates all possible keys then return null
706                 protected virtual AsymmetricAlgorithm GetPublicKey () 
707                 {
708                         if (m_signature.KeyInfo == null)
709                                 return null;
710
711                         if (pkEnumerator == null) {
712                                 pkEnumerator = m_signature.KeyInfo.GetEnumerator ();
713                         }
714                         
715 #if SECURITY_DEP
716                         if (_x509Enumerator != null) {
717                                 if (_x509Enumerator.MoveNext ()) {
718                                         X509Certificate cert = (X509Certificate) _x509Enumerator.Current;
719                                         return new X509Certificate2 (cert.GetRawCertData ()).PublicKey.Key;
720                                 } else {
721                                         _x509Enumerator = null;
722                                 }
723                         }
724 #endif
725                         while (pkEnumerator.MoveNext ()) {
726                                 AsymmetricAlgorithm key = null;
727                                 KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current;
728
729                                 if (kic is DSAKeyValue)
730                                         key = DSA.Create ();
731                                 else if (kic is RSAKeyValue) 
732                                         key = RSA.Create ();
733
734                                 if (key != null) {
735                                         key.FromXmlString (kic.GetXml ().InnerXml);
736                                         return key;
737                                 }
738
739 #if SECURITY_DEP
740                                 if (kic is KeyInfoX509Data) {
741                                         _x509Enumerator = ((KeyInfoX509Data) kic).Certificates.GetEnumerator ();
742                                         if (_x509Enumerator.MoveNext ()) {
743                                                 X509Certificate cert = (X509Certificate) _x509Enumerator.Current;
744                                                 return new X509Certificate2 (cert.GetRawCertData ()).PublicKey.Key;
745                                         }
746                                 }
747 #endif
748                         }
749                         return null;
750                 }
751
752                 public XmlElement GetXml () 
753                 {
754                         return m_signature.GetXml (envdoc);
755                 }
756
757                 public void LoadXml (XmlElement value) 
758                 {
759                         if (value == null)
760                                 throw new ArgumentNullException ("value");
761
762                         signatureElement = value;
763                         m_signature.LoadXml (value);
764                         // Need to give the EncryptedXml object to the 
765                         // XmlDecryptionTransform to give it a fighting 
766                         // chance at decrypting the document.
767                         foreach (Reference r in m_signature.SignedInfo.References) {
768                                 foreach (Transform t in r.TransformChain) {
769                                         if (t is XmlDecryptionTransform) 
770                                                 ((XmlDecryptionTransform) t).EncryptedXml = EncryptedXml;
771                                 }
772                         }
773                 }
774
775                 [ComVisible (false)]
776                 public XmlResolver Resolver {
777                         set { xmlResolver = value; }
778                 }
779         }
780 }