SignedXml.cs 11 KB

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