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