SignedXml.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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.SetHashAlgorithm (sd.DigestAlgorithm);
  190. result = verifier.VerifySignature (hash, signature.SignatureValue);
  191. }
  192. else
  193. result = false;
  194. }
  195. return result;
  196. }
  197. private bool Compare (byte[] expected, byte[] actual)
  198. {
  199. bool result = ((expected != null) && (actual != null));
  200. if (result) {
  201. int l = expected.Length;
  202. result = (l == actual.Length);
  203. if (result) {
  204. for (int i=0; i < l; i++) {
  205. if (expected[i] != actual[i])
  206. return false;
  207. }
  208. }
  209. }
  210. return result;
  211. }
  212. public bool CheckSignature (KeyedHashAlgorithm macAlg)
  213. {
  214. if (macAlg == null)
  215. throw new ArgumentNullException ("macAlg");
  216. // Part 1: Are all references digest valid ?
  217. bool result = CheckReferenceIntegrity ();
  218. if (result) {
  219. // Part 2: Is the signature (over SignedInfo) valid ?
  220. byte[] actual = macAlg.ComputeHash (SignedInfoTransformed ());
  221. result = Compare (signature.SignatureValue, actual);
  222. }
  223. return result;
  224. }
  225. public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey)
  226. {
  227. // here's the key used for verifying the signature
  228. if (key == null)
  229. key = GetPublicKey ();
  230. signingKey = key;
  231. // we'll find the key if we haven't already
  232. return CheckSignature (key);
  233. }
  234. public void ComputeSignature ()
  235. {
  236. if (key != null) {
  237. // required before hashing
  238. signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm;
  239. DigestReferences ();
  240. SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (signature.SignedInfo.SignatureMethod);
  241. // the hard part - C14Ning the KeyInfo
  242. byte[] hash = Hash (sd.DigestAlgorithm);
  243. AsymmetricSignatureFormatter signer = null;
  244. // in need for a CryptoConfig factory
  245. if (key is DSA)
  246. signer = new DSASignatureFormatter (key);
  247. else if (key is RSA)
  248. signer = new RSAPKCS1SignatureFormatter (key);
  249. if (signer != null) {
  250. signer.SetHashAlgorithm ("SHA1");
  251. signature.SignatureValue = signer.CreateSignature (hash);
  252. }
  253. }
  254. }
  255. public void ComputeSignature (KeyedHashAlgorithm macAlg)
  256. {
  257. if (macAlg == null)
  258. throw new ArgumentNullException ("macAlg");
  259. if (macAlg is HMACSHA1) {
  260. DigestReferences ();
  261. signature.SignedInfo.SignatureMethod = XmlDsigHMACSHA1Url;
  262. signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ());
  263. }
  264. else
  265. throw new CryptographicException ("unsupported algorithm");
  266. }
  267. // is that all ?
  268. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  269. {
  270. return document.GetElementById (idValue);
  271. }
  272. protected virtual AsymmetricAlgorithm GetPublicKey ()
  273. {
  274. AsymmetricAlgorithm key = null;
  275. if (signature.KeyInfo != null) {
  276. foreach (KeyInfoClause kic in signature.KeyInfo) {
  277. if (kic is DSAKeyValue)
  278. key = DSA.Create ();
  279. else if (kic is RSAKeyValue)
  280. key = RSA.Create ();
  281. if (key != null) {
  282. key.FromXmlString (kic.GetXml ().InnerXml);
  283. break;
  284. }
  285. }
  286. }
  287. return key;
  288. }
  289. public XmlElement GetXml ()
  290. {
  291. return signature.GetXml ();
  292. }
  293. public void LoadXml (XmlElement value)
  294. {
  295. signature.LoadXml (value);
  296. }
  297. #if ! NET_1_0
  298. private XmlResolver xmlResolver;
  299. [MonoTODO("property not (yet) used in class")]
  300. [ComVisible(false)]
  301. XmlResolver Resolver {
  302. set { xmlResolver = value; }
  303. }
  304. #endif
  305. }
  306. }