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