EncryptedXml.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. //
  2. // EncryptedXml.cs - EncryptedXml implementation for XML Encryption
  3. //
  4. // Author:
  5. // Tim Coleman ([email protected])
  6. //
  7. // Copyright (C) Tim Coleman, 2004
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. #if NET_2_0
  29. using System.Collections;
  30. using System.IO;
  31. using System.Security.Cryptography;
  32. using System.Security.Cryptography.X509Certificates;
  33. using System.Security.Policy;
  34. using System.Text;
  35. using System.Xml;
  36. namespace System.Security.Cryptography.Xml {
  37. public class EncryptedXml {
  38. #region Fields
  39. public const string XmlEncAES128KeyWrapUrl = XmlEncNamespaceUrl + "kw-aes128";
  40. public const string XmlEncAES128Url = XmlEncNamespaceUrl + "aes128-cbc";
  41. public const string XmlEncAES192KeyWrapUrl = XmlEncNamespaceUrl + "kw-aes192";
  42. public const string XmlEncAES192Url = XmlEncNamespaceUrl + "aes192-cbc";
  43. public const string XmlEncAES256KeyWrapUrl = XmlEncNamespaceUrl + "kw-aes256";
  44. public const string XmlEncAES256Url = XmlEncNamespaceUrl + "aes256-cbc";
  45. public const string XmlEncDESUrl = XmlEncNamespaceUrl + "des-cbc";
  46. public const string XmlEncElementContentUrl = XmlEncNamespaceUrl + "Content";
  47. public const string XmlEncElementUrl = XmlEncNamespaceUrl + "Element";
  48. public const string XmlEncEncryptedKeyUrl = XmlEncNamespaceUrl + "EncryptedKey";
  49. public const string XmlEncNamespaceUrl = "http://www.w3.org/2001/04/xmlenc#";
  50. public const string XmlEncRSA15Url = XmlEncNamespaceUrl + "rsa-1_5";
  51. public const string XmlEncRSAOAEPUrl = XmlEncNamespaceUrl + "rsa-oaep-mgf1p";
  52. public const string XmlEncSHA256Url = XmlEncNamespaceUrl + "sha256";
  53. public const string XmlEncSHA512Url = XmlEncNamespaceUrl + "sha512";
  54. public const string XmlEncTripleDESKeyWrapUrl = XmlEncNamespaceUrl + "kw-tripledes";
  55. public const string XmlEncTripleDESUrl = XmlEncNamespaceUrl + "tripledes-cbc";
  56. Evidence documentEvidence;
  57. Encoding encoding = Encoding.UTF8;
  58. internal Hashtable keyNameMapping = new Hashtable ();
  59. CipherMode mode = CipherMode.CBC;
  60. PaddingMode padding = PaddingMode.ISO10126;
  61. string recipient;
  62. XmlResolver resolver;
  63. XmlDocument document;
  64. #endregion // Fields
  65. #region Constructors
  66. [MonoTODO]
  67. public EncryptedXml ()
  68. {
  69. }
  70. [MonoTODO]
  71. public EncryptedXml (XmlDocument document)
  72. {
  73. this.document = document;
  74. }
  75. [MonoTODO]
  76. public EncryptedXml (XmlDocument document, Evidence evidence)
  77. {
  78. this.document = document;
  79. DocumentEvidence = evidence;
  80. }
  81. #endregion // Constructors
  82. #region Properties
  83. public Evidence DocumentEvidence {
  84. get { return documentEvidence; }
  85. set { documentEvidence = value; }
  86. }
  87. public Encoding Encoding {
  88. get { return encoding; }
  89. set { encoding = value; }
  90. }
  91. public CipherMode Mode {
  92. get { return mode; }
  93. set { mode = value; }
  94. }
  95. public PaddingMode Padding {
  96. get { return padding; }
  97. set { padding = value; }
  98. }
  99. public string Recipient {
  100. get { return recipient; }
  101. set { recipient = value; }
  102. }
  103. public XmlResolver Resolver {
  104. get { return resolver; }
  105. set { resolver = value; }
  106. }
  107. #endregion // Properties
  108. #region Methods
  109. public void AddKeyNameMapping (string keyName, object keyObject)
  110. {
  111. keyNameMapping [keyName] = keyObject;
  112. }
  113. public void ClearKeyNameMappings ()
  114. {
  115. keyNameMapping.Clear ();
  116. }
  117. public byte[] DecryptData (EncryptedData encryptedData, SymmetricAlgorithm symAlg)
  118. {
  119. return Transform (encryptedData.CipherData.CipherValue, symAlg.CreateDecryptor (), symAlg.BlockSize / 8);
  120. }
  121. public void DecryptDocument ()
  122. {
  123. XmlNodeList nodes = document.GetElementsByTagName ("EncryptedData", XmlEncNamespaceUrl);
  124. foreach (XmlNode node in nodes) {
  125. EncryptedData encryptedData = new EncryptedData ();
  126. encryptedData.LoadXml ((XmlElement) node);
  127. SymmetricAlgorithm symAlg = GetDecryptionKey (encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm);
  128. ReplaceData ((XmlElement) node, DecryptData (encryptedData, symAlg));
  129. }
  130. }
  131. public virtual byte[] DecryptEncryptedKey (EncryptedKey encryptedKey)
  132. {
  133. object keyAlg = null;
  134. foreach (KeyInfoClause innerClause in encryptedKey.KeyInfo) {
  135. if (innerClause is KeyInfoName) {
  136. keyAlg = keyNameMapping [((KeyInfoName) innerClause).Value];
  137. break;
  138. }
  139. }
  140. switch (encryptedKey.EncryptionMethod.KeyAlgorithm) {
  141. case XmlEncRSA15Url:
  142. return DecryptKey (encryptedKey.CipherData.CipherValue, (RSA) keyAlg, false);
  143. case XmlEncRSAOAEPUrl:
  144. return DecryptKey (encryptedKey.CipherData.CipherValue, (RSA) keyAlg, true);
  145. }
  146. return DecryptKey (encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm) keyAlg);
  147. }
  148. public static byte[] DecryptKey (byte[] keyData, SymmetricAlgorithm symAlg)
  149. {
  150. if (symAlg is TripleDES)
  151. return SymmetricKeyWrap.TripleDESKeyWrapDecrypt (symAlg.Key, keyData);
  152. if (symAlg is Rijndael)
  153. return SymmetricKeyWrap.AESKeyWrapDecrypt (symAlg.Key, keyData);
  154. throw new CryptographicException ("The specified cryptographic transform is not supported.");
  155. }
  156. [MonoTODO ("Test this.")]
  157. public static byte[] DecryptKey (byte[] keyData, RSA rsa, bool fOAEP)
  158. {
  159. AsymmetricKeyExchangeDeformatter deformatter = null;
  160. if (fOAEP)
  161. deformatter = new RSAOAEPKeyExchangeDeformatter (rsa);
  162. else
  163. deformatter = new RSAPKCS1KeyExchangeDeformatter (rsa);
  164. return deformatter.DecryptKeyExchange (keyData);
  165. }
  166. public EncryptedData Encrypt (XmlElement inputElement, string keyName)
  167. {
  168. // There are two keys of note here.
  169. // 1) KeyAlg: the key-encryption-key is used to wrap a key. The keyName
  170. // parameter will give us the KEK.
  171. // 2) SymAlg: A 256-bit AES key will be generated to encrypt the contents.
  172. // This key will be wrapped using the KEK.
  173. SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create ("Rijndael");
  174. symAlg.KeySize = 256;
  175. symAlg.GenerateKey ();
  176. symAlg.GenerateIV ();
  177. EncryptedData encryptedData = new EncryptedData ();
  178. EncryptedKey encryptedKey = new EncryptedKey();
  179. object keyAlg = keyNameMapping [keyName];
  180. encryptedKey.EncryptionMethod = new EncryptionMethod (GetKeyWrapAlgorithmUri (keyAlg));
  181. if (keyAlg is RSA)
  182. encryptedKey.CipherData = new CipherData (EncryptKey (symAlg.Key, (RSA) keyAlg, false));
  183. else
  184. encryptedKey.CipherData = new CipherData (EncryptKey (symAlg.Key, (SymmetricAlgorithm) keyAlg));
  185. encryptedKey.KeyInfo = new KeyInfo();
  186. encryptedKey.KeyInfo.AddClause (new KeyInfoName (keyName));
  187. encryptedData.Type = XmlEncElementUrl;
  188. encryptedData.EncryptionMethod = new EncryptionMethod (GetAlgorithmUri (symAlg));
  189. encryptedData.KeyInfo = new KeyInfo ();
  190. encryptedData.KeyInfo.AddClause (new KeyInfoEncryptedKey (encryptedKey));
  191. encryptedData.CipherData = new CipherData (EncryptData (inputElement, symAlg, false));
  192. return encryptedData;
  193. }
  194. [MonoTODO]
  195. public EncryptedData Encrypt (XmlElement inputElement, X509Certificate2 certificate)
  196. {
  197. throw new NotImplementedException ();
  198. }
  199. public byte[] EncryptData (byte[] plainText, SymmetricAlgorithm symAlg)
  200. {
  201. // Write the symmetric algorithm IV and ciphertext together.
  202. // We use a memory stream to accomplish this.
  203. MemoryStream stream = new MemoryStream ();
  204. BinaryWriter writer = new BinaryWriter (stream);
  205. writer.Write (symAlg.IV);
  206. writer.Write (Transform (plainText, symAlg.CreateEncryptor ()));
  207. writer.Flush ();
  208. byte [] output = stream.ToArray ();
  209. writer.Close ();
  210. stream.Close ();
  211. return output;
  212. }
  213. public byte[] EncryptData (XmlElement inputElement, SymmetricAlgorithm symAlg, bool content)
  214. {
  215. if (content)
  216. return EncryptData (Encoding.GetBytes (inputElement.InnerXml), symAlg);
  217. else
  218. return EncryptData (Encoding.GetBytes (inputElement.OuterXml), symAlg);
  219. }
  220. public static byte[] EncryptKey (byte[] keyData, SymmetricAlgorithm symAlg)
  221. {
  222. if (symAlg is TripleDES)
  223. return SymmetricKeyWrap.TripleDESKeyWrapEncrypt (symAlg.Key, keyData);
  224. if (symAlg is Rijndael)
  225. return SymmetricKeyWrap.AESKeyWrapEncrypt (symAlg.Key, keyData);
  226. throw new CryptographicException ("The specified cryptographic transform is not supported.");
  227. }
  228. [MonoTODO ("Test this.")]
  229. public static byte[] EncryptKey (byte[] keyData, RSA rsa, bool fOAEP)
  230. {
  231. AsymmetricKeyExchangeFormatter formatter = null;
  232. if (fOAEP)
  233. formatter = new RSAOAEPKeyExchangeFormatter (rsa);
  234. else
  235. formatter = new RSAPKCS1KeyExchangeFormatter (rsa);
  236. return formatter.CreateKeyExchange (keyData);
  237. }
  238. private static SymmetricAlgorithm GetAlgorithm (string symAlgUri)
  239. {
  240. SymmetricAlgorithm symAlg = null;
  241. switch (symAlgUri) {
  242. case XmlEncAES128Url:
  243. case XmlEncAES128KeyWrapUrl:
  244. symAlg = SymmetricAlgorithm.Create ("Rijndael");
  245. symAlg.KeySize = 128;
  246. break;
  247. case XmlEncAES192Url:
  248. case XmlEncAES192KeyWrapUrl:
  249. symAlg = SymmetricAlgorithm.Create ("Rijndael");
  250. symAlg.KeySize = 192;
  251. break;
  252. case XmlEncAES256Url:
  253. case XmlEncAES256KeyWrapUrl:
  254. symAlg = SymmetricAlgorithm.Create ("Rijndael");
  255. symAlg.KeySize = 256;
  256. break;
  257. case XmlEncDESUrl:
  258. symAlg = SymmetricAlgorithm.Create ("DES");
  259. break;
  260. case XmlEncTripleDESUrl:
  261. case XmlEncTripleDESKeyWrapUrl:
  262. symAlg = SymmetricAlgorithm.Create ("TripleDES");
  263. break;
  264. default:
  265. throw new ArgumentException ("symAlgUri");
  266. }
  267. return symAlg;
  268. }
  269. private static string GetAlgorithmUri (SymmetricAlgorithm symAlg)
  270. {
  271. if (symAlg is Rijndael)
  272. {
  273. switch (symAlg.KeySize) {
  274. case 128:
  275. return XmlEncAES128Url;
  276. case 192:
  277. return XmlEncAES192Url;
  278. case 256:
  279. return XmlEncAES256Url;
  280. }
  281. }
  282. else if (symAlg is DES)
  283. return XmlEncDESUrl;
  284. else if (symAlg is TripleDES)
  285. return XmlEncTripleDESUrl;
  286. throw new ArgumentException ("symAlg");
  287. }
  288. private static string GetKeyWrapAlgorithmUri (object keyAlg)
  289. {
  290. if (keyAlg is Rijndael)
  291. {
  292. switch (((Rijndael) keyAlg).KeySize) {
  293. case 128:
  294. return XmlEncAES128KeyWrapUrl;
  295. case 192:
  296. return XmlEncAES192KeyWrapUrl;
  297. case 256:
  298. return XmlEncAES256KeyWrapUrl;
  299. }
  300. }
  301. else if (keyAlg is RSA)
  302. return XmlEncRSA15Url;
  303. else if (keyAlg is TripleDES)
  304. return XmlEncTripleDESKeyWrapUrl;
  305. throw new ArgumentException ("keyAlg");
  306. }
  307. public virtual byte[] GetDecryptionIV (EncryptedData encryptedData, string symAlgUri)
  308. {
  309. SymmetricAlgorithm symAlg = GetAlgorithm (symAlgUri);
  310. byte[] iv = new Byte [symAlg.BlockSize / 8];
  311. Buffer.BlockCopy (encryptedData.CipherData.CipherValue, 0, iv, 0, iv.Length);
  312. return iv;
  313. }
  314. public virtual SymmetricAlgorithm GetDecryptionKey (EncryptedData encryptedData, string symAlgUri)
  315. {
  316. SymmetricAlgorithm symAlg = GetAlgorithm (symAlgUri);
  317. symAlg.IV = GetDecryptionIV (encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm);
  318. KeyInfo keyInfo = encryptedData.KeyInfo;
  319. foreach (KeyInfoClause clause in keyInfo) {
  320. if (clause is KeyInfoEncryptedKey) {
  321. symAlg.Key = DecryptEncryptedKey (((KeyInfoEncryptedKey) clause).EncryptedKey);
  322. break;
  323. }
  324. }
  325. return symAlg;
  326. }
  327. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  328. {
  329. // this works only if there's a DTD or XSD available to define the ID
  330. XmlElement xel = document.GetElementById (idValue);
  331. if (xel == null) {
  332. // search an "undefined" ID
  333. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  334. }
  335. return xel;
  336. }
  337. public void ReplaceData (XmlElement inputElement, byte[] decryptedData)
  338. {
  339. XmlDocument ownerDocument = inputElement.OwnerDocument;
  340. XmlTextReader reader = new XmlTextReader (new StringReader (Encoding.GetString (decryptedData, 0, decryptedData.Length)));
  341. reader.MoveToContent ();
  342. XmlNode node = ownerDocument.ReadNode (reader);
  343. inputElement.ParentNode.ReplaceChild (node, inputElement);
  344. }
  345. public static void ReplaceElement (XmlElement inputElement, EncryptedData encryptedData, bool content)
  346. {
  347. XmlDocument ownerDocument = inputElement.OwnerDocument;
  348. inputElement.ParentNode.ReplaceChild (encryptedData.GetXml (ownerDocument), inputElement);
  349. }
  350. private byte[] Transform (byte[] data, ICryptoTransform transform)
  351. {
  352. return Transform (data, transform, 0);
  353. }
  354. private byte[] Transform (byte[] data, ICryptoTransform transform, int startIndex)
  355. {
  356. MemoryStream output = new MemoryStream ();
  357. CryptoStream crypto = new CryptoStream (output, transform, CryptoStreamMode.Write);
  358. crypto.Write (data, startIndex, data.Length - startIndex);
  359. crypto.FlushFinalBlock ();
  360. byte[] result = output.ToArray ();
  361. crypto.Close ();
  362. output.Close ();
  363. return result;
  364. }
  365. #endregion // Methods
  366. }
  367. }
  368. #endif