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