SignedXml.cs 8.9 KB

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