SignedXml.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. //
  2. // SignedXml.cs - SignedXml implementation for XML Signature
  3. //
  4. // Author:
  5. // Sebastien Pouliot ([email protected])
  6. //
  7. // (C) 2002 Motus Technologies Inc. (http://www.motus.com)
  8. //
  9. using System.Collections;
  10. using System.IO;
  11. using System.Security.Cryptography;
  12. using System.Text;
  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 = "http://www.w3.org/2000/09/xmldsig#sha1";
  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. [MonoTODO("Become hash algorithm independant")]
  155. private byte[] Hash ()
  156. {
  157. // we must select the hash using ??? SignatureMethod (yuck)
  158. // FIXME: Hardcoded to SHA1 - which is, right now, the only digest defined in XMLDSIG
  159. SHA1 sha = SHA1.Create ();
  160. // get the hash of the C14N SignedInfo element
  161. return sha.ComputeHash (SignedInfoTransformed ());
  162. }
  163. public bool CheckSignature ()
  164. {
  165. // CryptographicException
  166. if (key == null)
  167. key = GetPublicKey ();
  168. return CheckSignature (key);
  169. }
  170. private bool CheckReferenceIntegrity ()
  171. {
  172. // check digest (hash) for every reference
  173. foreach (Reference r in signature.SignedInfo.References) {
  174. // stop at first broken reference
  175. if (! Compare (r.DigestValue, GetReferenceHash (r)))
  176. return false;
  177. }
  178. return true;
  179. }
  180. public bool CheckSignature (AsymmetricAlgorithm key)
  181. {
  182. if (key == null)
  183. throw new ArgumentNullException ("key");
  184. // Part 1: Are all references digest valid ?
  185. bool result = CheckReferenceIntegrity ();
  186. if (result) {
  187. // Part 2: Is the signature (over SignedInfo) valid ?
  188. byte[] hash = Hash ();
  189. AsymmetricSignatureDeformatter verifier = null;
  190. if (key is DSA)
  191. verifier = new DSASignatureDeformatter (key);
  192. else if (key is RSA)
  193. verifier = new RSAPKCS1SignatureDeformatter (key);
  194. else
  195. result = false;
  196. if (verifier != null) {
  197. verifier.SetHashAlgorithm ("SHA1");
  198. result = verifier.VerifySignature (hash, signature.SignatureValue);
  199. }
  200. }
  201. return result;
  202. }
  203. private bool Compare (byte[] expected, byte[] actual)
  204. {
  205. bool result = ((expected != null) && (actual != null));
  206. if (result) {
  207. int l = expected.Length;
  208. result = (l == actual.Length);
  209. if (result) {
  210. for (int i=0; i < l; i++) {
  211. if (expected[i] != actual[i])
  212. return false;
  213. }
  214. }
  215. }
  216. return result;
  217. }
  218. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  219. {
  220. if (macAlg == null)
  221. throw new ArgumentNullException ("macAlg");
  222. // Part 1: Are all references digest valid ?
  223. bool result = CheckReferenceIntegrity ();
  224. if (result) {
  225. // Part 2: Is the signature (over SignedInfo) valid ?
  226. byte[] actual = macAlg.ComputeHash (SignedInfoTransformed ());
  227. result = Compare (signature.SignatureValue, actual);
  228. }
  229. return result;
  230. }
  231. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  232. {
  233. // here's the key used for verifying the signature
  234. if (key == null)
  235. key = GetPublicKey ();
  236. signingKey = key;
  237. // we'll find the key if we haven't already
  238. return CheckSignature (key);
  239. }
  240. public void ComputeSignature ()
  241. {
  242. if (key != null) {
  243. // required before hashing
  244. signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  245. DigestReferences ();
  246. // the hard part - C14Ning the KeyInfo
  247. byte[] hash = Hash ();
  248. AsymmetricSignatureFormatter signer = null;
  249. // in need for a CryptoConfig factory
  250. if (key is DSA)
  251. signer = new DSASignatureFormatter (key);
  252. else if (key is RSA)
  253. signer = new RSAPKCS1SignatureFormatter (key);
  254. if (signer != null) {
  255. signer.SetHashAlgorithm ("SHA1");
  256. signature.SignatureValue = signer.CreateSignature (hash);
  257. }
  258. }
  259. }
  260. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  261. {
  262. if (macAlg == null)
  263. throw new ArgumentNullException ("macAlg");
  264. if (macAlg is HMACSHA1) {
  265. DigestReferences ();
  266. signature.SignedInfo.SignatureMethod = "http://www.w3.org/2000/09/xmldsig#hmac-sha1";
  267. signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  268. }
  269. else
  270. throw new CryptographicException ("unsupported algorithm");
  271. }
  272. // is that all ?
  273. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  274. {
  275. return document.GetElementById (idValue);
  276. }
  277. protected virtual AsymmetricAlgorithm GetPublicKey ()
  278. {
  279. AsymmetricAlgorithm key = null;
  280. if (signature.KeyInfo != null) {
  281. foreach (KeyInfoClause kic in signature.KeyInfo) {
  282. if (kic is DSAKeyValue)
  283. key = DSA.Create ();
  284. else if (kic is RSAKeyValue)
  285. key = RSA.Create ();
  286. if (key != null) {
  287. key.FromXmlString (kic.GetXml ().InnerXml);
  288. break;
  289. }
  290. }
  291. }
  292. return key;
  293. }
  294. public XmlElement GetXml ()
  295. {
  296. return signature.GetXml ();
  297. }
  298. public void LoadXml (XmlElement value)
  299. {
  300. signature.LoadXml (value);
  301. }
  302. }
  303. }