SignedXml.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. //
  2. // SignedXml.cs - SignedXml implementation for XML Signature
  3. //
  4. // Author:
  5. // Sebastien Pouliot ([email protected])
  6. //
  7. // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
  8. //
  9. using System.Collections;
  10. using System.IO;
  11. using System.Runtime.InteropServices;
  12. using System.Security.Cryptography;
  13. using System.Xml;
  14. namespace System.Security.Cryptography.Xml {
  15. public class SignedXml {
  16. private Signature signature;
  17. private AsymmetricAlgorithm key;
  18. private string keyName;
  19. private XmlDocument envdoc;
  20. public SignedXml ()
  21. {
  22. signature = new Signature ();
  23. signature.SignedInfo = new SignedInfo ();
  24. }
  25. public SignedXml (XmlDocument document)
  26. {
  27. signature = new Signature ();
  28. signature.SignedInfo = new SignedInfo ();
  29. envdoc = document;
  30. }
  31. public SignedXml (XmlElement elem) : this ()
  32. {
  33. if (elem == null)
  34. throw new ArgumentNullException ("elem");
  35. signature = new Signature ();
  36. signature.SignedInfo = new SignedInfo ();
  37. }
  38. public const string XmlDsigCanonicalizationUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
  39. public const string XmlDsigCanonicalizationWithCommentsUrl = XmlDsigCanonicalizationUrl + "#WithComments";
  40. public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#";
  41. public const string XmlDsigDSAUrl = XmlDsigNamespaceUrl + "dsa-sha1";
  42. public const string XmlDsigHMACSHA1Url = XmlDsigNamespaceUrl + "hmac-sha1";
  43. public const string XmlDsigMinimalCanonicalizationUrl = XmlDsigNamespaceUrl + "minimal";
  44. public const string XmlDsigRSASHA1Url = XmlDsigNamespaceUrl + "rsa-sha1";
  45. public const string XmlDsigSHA1Url = XmlDsigNamespaceUrl + "sha1";
  46. public KeyInfo KeyInfo {
  47. get { return signature.KeyInfo; }
  48. set { signature.KeyInfo = value; }
  49. }
  50. public Signature Signature {
  51. get { return signature; }
  52. }
  53. public string SignatureLength {
  54. get { return signature.SignedInfo.SignatureLength; }
  55. }
  56. public string SignatureMethod {
  57. get { return signature.SignedInfo.SignatureMethod; }
  58. }
  59. public byte[] SignatureValue {
  60. get { return signature.SignatureValue; }
  61. }
  62. public SignedInfo SignedInfo {
  63. get { return signature.SignedInfo; }
  64. }
  65. public AsymmetricAlgorithm SigningKey {
  66. get { return key; }
  67. set { key = value; }
  68. }
  69. public string SigningKeyName {
  70. get { return keyName; }
  71. set { keyName = value; }
  72. }
  73. public void AddObject (DataObject dataObject)
  74. {
  75. signature.AddObject (dataObject);
  76. }
  77. public void AddReference (Reference reference)
  78. {
  79. signature.SignedInfo.AddReference (reference);
  80. }
  81. private Stream ApplyTransform (Transform t, XmlDocument doc)
  82. {
  83. t.LoadInput (doc);
  84. if (t is XmlDsigEnvelopedSignatureTransform) {
  85. XmlDocument d = (XmlDocument) t.GetOutput ();
  86. MemoryStream ms = new MemoryStream ();
  87. d.Save (ms);
  88. return ms;
  89. }
  90. else
  91. return (Stream) t.GetOutput ();
  92. }
  93. private Stream ApplyTransform (Transform t, Stream s)
  94. {
  95. try {
  96. t.LoadInput (s);
  97. s = (Stream) t.GetOutput ();
  98. }
  99. catch (Exception e) {
  100. string temp = e.ToString (); // stop debugger
  101. }
  102. return s;
  103. }
  104. [MonoTODO("incomplete")]
  105. private byte[] GetReferenceHash (Reference r)
  106. {
  107. XmlDocument doc = new XmlDocument ();
  108. doc.PreserveWhitespace = true;
  109. if (r.Uri == "")
  110. doc = envdoc;
  111. else {
  112. foreach (DataObject obj in signature.ObjectList) {
  113. if ("#" + obj.Id == r.Uri) {
  114. doc.LoadXml (obj.GetXml ().OuterXml);
  115. break;
  116. }
  117. }
  118. }
  119. Stream s = null;
  120. if (r.TransformChain.Count > 0) {
  121. foreach (Transform t in r.TransformChain) {
  122. if (s == null)
  123. s = ApplyTransform (t, doc);
  124. else
  125. s = ApplyTransform (t, s);
  126. }
  127. }
  128. else
  129. s = ApplyTransform (new XmlDsigC14NTransform (), doc);
  130. // TODO: We should reuse the same hash object (when possible)
  131. HashAlgorithm hash = (HashAlgorithm) CryptoConfig.CreateFromName (r.DigestMethod);
  132. return hash.ComputeHash (s);
  133. }
  134. private void DigestReferences ()
  135. {
  136. // we must tell each reference which hash algorithm to use
  137. // before asking for the SignedInfo XML !
  138. foreach (Reference r in signature.SignedInfo.References) {
  139. // assume SHA-1 if nothing is specified
  140. if (r.DigestMethod == null)
  141. r.DigestMethod = XmlDsigSHA1Url;
  142. r.DigestValue = GetReferenceHash (r);
  143. }
  144. }
  145. private Stream SignedInfoTransformed ()
  146. {
  147. Transform t = (Transform) CryptoConfig.CreateFromName (signature.SignedInfo.CanonicalizationMethod);
  148. if (t == null)
  149. return null;
  150. XmlDocument doc = new XmlDocument ();
  151. doc.LoadXml (signature.SignedInfo.GetXml ().OuterXml);
  152. return ApplyTransform (t, doc);
  153. }
  154. private byte[] Hash (string hashAlgorithm)
  155. {
  156. HashAlgorithm hash = HashAlgorithm.Create (hashAlgorithm);
  157. // get the hash of the C14N SignedInfo element
  158. return hash.ComputeHash (SignedInfoTransformed ());
  159. }
  160. public bool CheckSignature ()
  161. {
  162. // CryptographicException
  163. if (key == null)
  164. key = GetPublicKey ();
  165. return CheckSignature (key);
  166. }
  167. private bool CheckReferenceIntegrity ()
  168. {
  169. // check digest (hash) for every reference
  170. foreach (Reference r in signature.SignedInfo.References) {
  171. // stop at first broken reference
  172. if (! Compare (r.DigestValue, GetReferenceHash (r)))
  173. return false;
  174. }
  175. return true;
  176. }
  177. public bool CheckSignature (AsymmetricAlgorithm key)
  178. {
  179. if (key == null)
  180. throw new ArgumentNullException ("key");
  181. // Part 1: Are all references digest valid ?
  182. bool result = CheckReferenceIntegrity ();
  183. if (result) {
  184. // Part 2: Is the signature (over SignedInfo) valid ?
  185. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  186. byte[] hash = Hash (sd.DigestAlgorithm);
  187. AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm);
  188. if (verifier != null) {
  189. verifier.SetKey (key);
  190. verifier.SetHashAlgorithm (sd.DigestAlgorithm);
  191. result = verifier.VerifySignature (hash, signature.SignatureValue);
  192. }
  193. else
  194. result = false;
  195. }
  196. return result;
  197. }
  198. private bool Compare (byte[] expected, byte[] actual)
  199. {
  200. bool result = ((expected != null) && (actual != null));
  201. if (result) {
  202. int l = expected.Length;
  203. result = (l == actual.Length);
  204. if (result) {
  205. for (int i=0; i < l; i++) {
  206. if (expected[i] != actual[i])
  207. return false;
  208. }
  209. }
  210. }
  211. return result;
  212. }
  213. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  214. {
  215. if (macAlg == null)
  216. throw new ArgumentNullException ("macAlg");
  217. // Part 1: Are all references digest valid ?
  218. bool result = CheckReferenceIntegrity ();
  219. if (result) {
  220. // Part 2: Is the signature (over SignedInfo) valid ?
  221. byte[] actual = macAlg.ComputeHash (SignedInfoTransformed ());
  222. result = Compare (signature.SignatureValue, actual);
  223. }
  224. return result;
  225. }
  226. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  227. {
  228. // here's the key used for verifying the signature
  229. if (key == null)
  230. key = GetPublicKey ();
  231. signingKey = key;
  232. // we'll find the key if we haven't already
  233. return CheckSignature (key);
  234. }
  235. public void ComputeSignature ()
  236. {
  237. if (key != null) {
  238. // required before hashing
  239. signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  240. DigestReferences ();
  241. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  242. // the hard part - C14Ning the KeyInfo
  243. byte[] hash = Hash (sd.DigestAlgorithm);
  244. AsymmetricSignatureFormatter signer = null;
  245. // in need for a CryptoConfig factory
  246. if (key is DSA)
  247. signer = new DSASignatureFormatter (key);
  248. else if (key is RSA)
  249. signer = new RSAPKCS1SignatureFormatter (key);
  250. if (signer != null) {
  251. signer.SetHashAlgorithm ("SHA1");
  252. signature.SignatureValue = signer.CreateSignature (hash);
  253. }
  254. }
  255. }
  256. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  257. {
  258. if (macAlg == null)
  259. throw new ArgumentNullException ("macAlg");
  260. if (macAlg is HMACSHA1) {
  261. DigestReferences ();
  262. signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  263. signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  264. }
  265. else
  266. throw new CryptographicException ("unsupported algorithm");
  267. }
  268. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  269. {
  270. // this works only if there's a DTD or XSD available to define the ID
  271. XmlElement xel = document.GetElementById (idValue);
  272. if (xel == null) {
  273. // search an "undefined" ID
  274. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  275. }
  276. return xel;
  277. }
  278. protected virtual AsymmetricAlgorithm GetPublicKey ()
  279. {
  280. AsymmetricAlgorithm key = null;
  281. if (signature.KeyInfo != null) {
  282. foreach (KeyInfoClause kic in signature.KeyInfo) {
  283. if (kic is DSAKeyValue)
  284. key = DSA.Create ();
  285. else if (kic is RSAKeyValue)
  286. key = RSA.Create ();
  287. if (key != null) {
  288. key.FromXmlString (kic.GetXml ().InnerXml);
  289. break;
  290. }
  291. }
  292. }
  293. return key;
  294. }
  295. public XmlElement GetXml ()
  296. {
  297. return signature.GetXml ();
  298. }
  299. public void LoadXml (XmlElement value)
  300. {
  301. signature.LoadXml (value);
  302. }
  303. #if ! NET_1_0
  304. private XmlResolver xmlResolver;
  305. [MonoTODO("property not (yet) used in class")]
  306. [ComVisible(false)]
  307. public XmlResolver Resolver {
  308. set { xmlResolver = value; }
  309. }
  310. #endif
  311. }
  312. }