EncryptedXml.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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, true);
  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. PaddingMode bak = symAlg.Padding;
  202. try {
  203. symAlg.Padding = PaddingMode.ISO10126;
  204. return EncryptDataCore (plainText, symAlg);
  205. } finally {
  206. symAlg.Padding = bak;
  207. }
  208. }
  209. byte[] EncryptDataCore (byte[] plainText, SymmetricAlgorithm symAlg)
  210. {
  211. // Write the symmetric algorithm IV and ciphertext together.
  212. // We use a memory stream to accomplish this.
  213. MemoryStream stream = new MemoryStream ();
  214. BinaryWriter writer = new BinaryWriter (stream);
  215. writer.Write (symAlg.IV);
  216. writer.Write (Transform (plainText, symAlg.CreateEncryptor ()));
  217. writer.Flush ();
  218. byte [] output = stream.ToArray ();
  219. writer.Close ();
  220. stream.Close ();
  221. return output;
  222. }
  223. public byte[] EncryptData (XmlElement inputElement, SymmetricAlgorithm symAlg, bool content)
  224. {
  225. if (content)
  226. return EncryptData (Encoding.GetBytes (inputElement.InnerXml), symAlg);
  227. else
  228. return EncryptData (Encoding.GetBytes (inputElement.OuterXml), symAlg);
  229. }
  230. public static byte[] EncryptKey (byte[] keyData, SymmetricAlgorithm symAlg)
  231. {
  232. if (symAlg is TripleDES)
  233. return SymmetricKeyWrap.TripleDESKeyWrapEncrypt (symAlg.Key, keyData);
  234. if (symAlg is Rijndael)
  235. return SymmetricKeyWrap.AESKeyWrapEncrypt (symAlg.Key, keyData);
  236. throw new CryptographicException ("The specified cryptographic transform is not supported.");
  237. }
  238. [MonoTODO ("Test this.")]
  239. public static byte[] EncryptKey (byte[] keyData, RSA rsa, bool fOAEP)
  240. {
  241. AsymmetricKeyExchangeFormatter formatter = null;
  242. if (fOAEP)
  243. formatter = new RSAOAEPKeyExchangeFormatter (rsa);
  244. else
  245. formatter = new RSAPKCS1KeyExchangeFormatter (rsa);
  246. return formatter.CreateKeyExchange (keyData);
  247. }
  248. private static SymmetricAlgorithm GetAlgorithm (string symAlgUri)
  249. {
  250. SymmetricAlgorithm symAlg = null;
  251. switch (symAlgUri) {
  252. case XmlEncAES128Url:
  253. case XmlEncAES128KeyWrapUrl:
  254. symAlg = SymmetricAlgorithm.Create ("Rijndael");
  255. symAlg.KeySize = 128;
  256. break;
  257. case XmlEncAES192Url:
  258. case XmlEncAES192KeyWrapUrl:
  259. symAlg = SymmetricAlgorithm.Create ("Rijndael");
  260. symAlg.KeySize = 192;
  261. break;
  262. case XmlEncAES256Url:
  263. case XmlEncAES256KeyWrapUrl:
  264. symAlg = SymmetricAlgorithm.Create ("Rijndael");
  265. symAlg.KeySize = 256;
  266. break;
  267. case XmlEncDESUrl:
  268. symAlg = SymmetricAlgorithm.Create ("DES");
  269. break;
  270. case XmlEncTripleDESUrl:
  271. case XmlEncTripleDESKeyWrapUrl:
  272. symAlg = SymmetricAlgorithm.Create ("TripleDES");
  273. break;
  274. default:
  275. throw new ArgumentException ("symAlgUri");
  276. }
  277. return symAlg;
  278. }
  279. private static string GetAlgorithmUri (SymmetricAlgorithm symAlg)
  280. {
  281. if (symAlg is Rijndael)
  282. {
  283. switch (symAlg.KeySize) {
  284. case 128:
  285. return XmlEncAES128Url;
  286. case 192:
  287. return XmlEncAES192Url;
  288. case 256:
  289. return XmlEncAES256Url;
  290. }
  291. }
  292. else if (symAlg is DES)
  293. return XmlEncDESUrl;
  294. else if (symAlg is TripleDES)
  295. return XmlEncTripleDESUrl;
  296. throw new ArgumentException ("symAlg");
  297. }
  298. private static string GetKeyWrapAlgorithmUri (object keyAlg)
  299. {
  300. if (keyAlg is Rijndael)
  301. {
  302. switch (((Rijndael) keyAlg).KeySize) {
  303. case 128:
  304. return XmlEncAES128KeyWrapUrl;
  305. case 192:
  306. return XmlEncAES192KeyWrapUrl;
  307. case 256:
  308. return XmlEncAES256KeyWrapUrl;
  309. }
  310. }
  311. else if (keyAlg is RSA)
  312. return XmlEncRSA15Url;
  313. else if (keyAlg is TripleDES)
  314. return XmlEncTripleDESKeyWrapUrl;
  315. throw new ArgumentException ("keyAlg");
  316. }
  317. public virtual byte[] GetDecryptionIV (EncryptedData encryptedData, string symAlgUri)
  318. {
  319. SymmetricAlgorithm symAlg = GetAlgorithm (symAlgUri);
  320. byte[] iv = new Byte [symAlg.BlockSize / 8];
  321. Buffer.BlockCopy (encryptedData.CipherData.CipherValue, 0, iv, 0, iv.Length);
  322. return iv;
  323. }
  324. public virtual SymmetricAlgorithm GetDecryptionKey (EncryptedData encryptedData, string symAlgUri)
  325. {
  326. SymmetricAlgorithm symAlg = GetAlgorithm (symAlgUri);
  327. symAlg.IV = GetDecryptionIV (encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm);
  328. KeyInfo keyInfo = encryptedData.KeyInfo;
  329. foreach (KeyInfoClause clause in keyInfo) {
  330. if (clause is KeyInfoEncryptedKey) {
  331. symAlg.Key = DecryptEncryptedKey (((KeyInfoEncryptedKey) clause).EncryptedKey);
  332. break;
  333. }
  334. }
  335. return symAlg;
  336. }
  337. public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
  338. {
  339. // this works only if there's a DTD or XSD available to define the ID
  340. XmlElement xel = document.GetElementById (idValue);
  341. if (xel == null) {
  342. // search an "undefined" ID
  343. xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
  344. }
  345. return xel;
  346. }
  347. public void ReplaceData (XmlElement inputElement, byte[] decryptedData)
  348. {
  349. XmlDocument ownerDocument = inputElement.OwnerDocument;
  350. XmlTextReader reader = new XmlTextReader (new StringReader (Encoding.GetString (decryptedData, 0, decryptedData.Length)));
  351. reader.MoveToContent ();
  352. XmlNode node = ownerDocument.ReadNode (reader);
  353. inputElement.ParentNode.ReplaceChild (node, inputElement);
  354. }
  355. public static void ReplaceElement (XmlElement inputElement, EncryptedData encryptedData, bool content)
  356. {
  357. XmlDocument ownerDocument = inputElement.OwnerDocument;
  358. inputElement.ParentNode.ReplaceChild (encryptedData.GetXml (ownerDocument), inputElement);
  359. }
  360. private byte[] Transform (byte[] data, ICryptoTransform transform)
  361. {
  362. return Transform (data, transform, 0, false);
  363. }
  364. private byte[] Transform (byte[] data, ICryptoTransform transform, int blockOctetCount, bool trimPadding)
  365. {
  366. MemoryStream output = new MemoryStream ();
  367. CryptoStream crypto = new CryptoStream (output, transform, CryptoStreamMode.Write);
  368. crypto.Write (data, 0, data.Length);
  369. crypto.FlushFinalBlock ();
  370. // strip padding (see xmlenc spec 5.2)
  371. int trimSize = 0;
  372. if (trimPadding)
  373. trimSize = output.GetBuffer () [output.Length - 1];
  374. // It should not happen, but somehow .NET allows such cipher
  375. // data as if there were no padding.
  376. if (trimSize > blockOctetCount)
  377. trimSize = 0;
  378. byte[] result = new byte [output.Length - blockOctetCount - trimSize];
  379. Array.Copy (output.GetBuffer (), blockOctetCount, result, 0, result.Length);
  380. crypto.Close ();
  381. output.Close ();
  382. return result;
  383. }
  384. #endregion // Methods
  385. }
  386. }
  387. #endif