File: EncryptedXml.cs

package info (click to toggle)
mono 1.2.2.1-1etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 142,720 kB
  • ctags: 256,408
  • sloc: cs: 1,495,736; ansic: 249,442; sh: 18,327; xml: 12,463; makefile: 5,046; perl: 1,248; asm: 635; yacc: 285; sql: 7
file content (462 lines) | stat: -rw-r--r-- 14,599 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//
// EncryptedXml.cs - EncryptedXml implementation for XML Encryption
//
// Author:
//      Tim Coleman (tim@timcoleman.com)
//
// Copyright (C) Tim Coleman, 2004

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#if NET_2_0

using System.Collections;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Policy;
using System.Text;
using System.Xml;

namespace System.Security.Cryptography.Xml {
	public class EncryptedXml {

		#region Fields

		public const string XmlEncAES128KeyWrapUrl	= XmlEncNamespaceUrl + "kw-aes128";
		public const string XmlEncAES128Url		= XmlEncNamespaceUrl + "aes128-cbc";
		public const string XmlEncAES192KeyWrapUrl	= XmlEncNamespaceUrl + "kw-aes192";
		public const string XmlEncAES192Url		= XmlEncNamespaceUrl + "aes192-cbc";
		public const string XmlEncAES256KeyWrapUrl	= XmlEncNamespaceUrl + "kw-aes256";
		public const string XmlEncAES256Url		= XmlEncNamespaceUrl + "aes256-cbc";
		public const string XmlEncDESUrl		= XmlEncNamespaceUrl + "des-cbc";
		public const string XmlEncElementContentUrl	= XmlEncNamespaceUrl + "Content";
		public const string XmlEncElementUrl		= XmlEncNamespaceUrl + "Element";
		public const string XmlEncEncryptedKeyUrl	= XmlEncNamespaceUrl + "EncryptedKey";
		public const string XmlEncNamespaceUrl		= "http://www.w3.org/2001/04/xmlenc#";
		public const string XmlEncRSA15Url		= XmlEncNamespaceUrl + "rsa-1_5";
		public const string XmlEncRSAOAEPUrl		= XmlEncNamespaceUrl + "rsa-oaep-mgf1p";
		public const string XmlEncSHA256Url		= XmlEncNamespaceUrl + "sha256";
		public const string XmlEncSHA512Url		= XmlEncNamespaceUrl + "sha512";
		public const string XmlEncTripleDESKeyWrapUrl	= XmlEncNamespaceUrl + "kw-tripledes";
		public const string XmlEncTripleDESUrl		= XmlEncNamespaceUrl + "tripledes-cbc";

		Evidence documentEvidence;
		Encoding encoding = Encoding.UTF8;
		internal Hashtable keyNameMapping = new Hashtable ();
		CipherMode mode = CipherMode.CBC;
		PaddingMode padding = PaddingMode.ISO10126;
		string recipient;
		XmlResolver resolver;
		XmlDocument document;

		#endregion // Fields
	
		#region Constructors

		[MonoTODO]
		public EncryptedXml ()
		{
		}

		[MonoTODO]
		public EncryptedXml (XmlDocument document)
		{
			this.document = document;
		}

		[MonoTODO]
		public EncryptedXml (XmlDocument document, Evidence evidence)
		{
			this.document = document;
			DocumentEvidence = evidence;
		}
	
		#endregion // Constructors
	
		#region Properties

		public Evidence DocumentEvidence {
			get { return documentEvidence; }
			set { documentEvidence = value; }
		}

		public Encoding Encoding {
			get { return encoding; }
			set { encoding = value; }
		}

		public CipherMode Mode {
			get { return mode; }
			set { mode = value; }
		}

		public PaddingMode Padding {
			get { return padding; }
			set { padding = value; }
		}

		public string Recipient {
			get { return recipient; }
			set { recipient = value; }
		}
		
		public XmlResolver Resolver {
			get { return resolver; }
			set { resolver = value; }
		}

		#endregion // Properties

		#region Methods

		public void AddKeyNameMapping (string keyName, object keyObject)
		{
			keyNameMapping [keyName] = keyObject;
		}

		public void ClearKeyNameMappings ()
		{
			keyNameMapping.Clear ();
		}

		public byte[] DecryptData (EncryptedData encryptedData, SymmetricAlgorithm symAlg)
		{
			PaddingMode bak = symAlg.Padding;
			try {
				symAlg.Padding = Padding;
				return Transform (encryptedData.CipherData.CipherValue, symAlg.CreateDecryptor (), symAlg.BlockSize / 8, true);
			} finally {
				symAlg.Padding = bak;
			}
		}

		public void DecryptDocument ()
		{
			XmlNodeList nodes = document.GetElementsByTagName ("EncryptedData", XmlEncNamespaceUrl);
			foreach (XmlNode node in nodes) {
				EncryptedData encryptedData = new EncryptedData ();
				encryptedData.LoadXml ((XmlElement) node);
				SymmetricAlgorithm symAlg = GetDecryptionKey (encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm);
				ReplaceData ((XmlElement) node, DecryptData (encryptedData, symAlg));
			}
		}

		public virtual byte[] DecryptEncryptedKey (EncryptedKey encryptedKey)
		{
			object keyAlg = null;
			foreach (KeyInfoClause innerClause in encryptedKey.KeyInfo) {
				if (innerClause is KeyInfoName) {
					keyAlg = keyNameMapping [((KeyInfoName) innerClause).Value];
					break;
				}
			}
			switch (encryptedKey.EncryptionMethod.KeyAlgorithm) {
			case XmlEncRSA15Url:
				return DecryptKey (encryptedKey.CipherData.CipherValue, (RSA) keyAlg, false);
			case XmlEncRSAOAEPUrl:
				return DecryptKey (encryptedKey.CipherData.CipherValue, (RSA) keyAlg, true);
			}
			return DecryptKey (encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm) keyAlg);
		}

		public static byte[] DecryptKey (byte[] keyData, SymmetricAlgorithm symAlg)
		{
			if (symAlg is TripleDES)
				return SymmetricKeyWrap.TripleDESKeyWrapDecrypt (symAlg.Key, keyData);
			if (symAlg is Rijndael)
				return SymmetricKeyWrap.AESKeyWrapDecrypt (symAlg.Key, keyData);
			throw new CryptographicException ("The specified cryptographic transform is not supported.");
		}

		[MonoTODO ("Test this.")]
		public static byte[] DecryptKey (byte[] keyData, RSA rsa, bool fOAEP)
		{
			AsymmetricKeyExchangeDeformatter deformatter = null;
			if (fOAEP) 
				deformatter = new RSAOAEPKeyExchangeDeformatter (rsa);
			else
				deformatter = new RSAPKCS1KeyExchangeDeformatter (rsa);
			return deformatter.DecryptKeyExchange (keyData);
		}

		public EncryptedData Encrypt (XmlElement inputElement, string keyName)
		{
			// There are two keys of note here.
			// 1) KeyAlg: the key-encryption-key is used to wrap a key.  The keyName
			//    parameter will give us the KEK.
			// 2) SymAlg: A 256-bit AES key will be generated to encrypt the contents.
			//    This key will be wrapped using the KEK.

			SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create ("Rijndael");
			symAlg.KeySize = 256;
			symAlg.GenerateKey ();
			symAlg.GenerateIV ();

			EncryptedData encryptedData = new EncryptedData ();
			EncryptedKey encryptedKey = new EncryptedKey();

			object keyAlg = keyNameMapping [keyName];

			encryptedKey.EncryptionMethod = new EncryptionMethod (GetKeyWrapAlgorithmUri (keyAlg));

			if (keyAlg is RSA)
				encryptedKey.CipherData = new CipherData (EncryptKey (symAlg.Key, (RSA) keyAlg, false));
			else
				encryptedKey.CipherData = new CipherData (EncryptKey (symAlg.Key, (SymmetricAlgorithm) keyAlg));

			encryptedKey.KeyInfo = new KeyInfo();
			encryptedKey.KeyInfo.AddClause (new KeyInfoName (keyName));
			
			encryptedData.Type = XmlEncElementUrl;
			encryptedData.EncryptionMethod = new EncryptionMethod (GetAlgorithmUri (symAlg));
			encryptedData.KeyInfo = new KeyInfo ();
			encryptedData.KeyInfo.AddClause (new KeyInfoEncryptedKey (encryptedKey));
			encryptedData.CipherData = new CipherData (EncryptData (inputElement, symAlg, false));

			return encryptedData;
		}
		
		[MonoTODO]
		public EncryptedData Encrypt (XmlElement inputElement, X509Certificate2 certificate)
		{
			throw new NotImplementedException ();
		}

		public byte[] EncryptData (byte[] plainText, SymmetricAlgorithm symAlg)
		{
			PaddingMode bak = symAlg.Padding;
			try {
				symAlg.Padding = Padding;
				return EncryptDataCore (plainText, symAlg);
			} finally {
				symAlg.Padding = bak;
			}
		}

		byte[] EncryptDataCore (byte[] plainText, SymmetricAlgorithm symAlg)
		{
			// Write the symmetric algorithm IV and ciphertext together.
			// We use a memory stream to accomplish this.
			MemoryStream stream = new MemoryStream ();
			BinaryWriter writer = new BinaryWriter (stream);

			writer.Write (symAlg.IV);
			writer.Write (Transform (plainText, symAlg.CreateEncryptor ()));
			writer.Flush ();

			byte [] output = stream.ToArray ();

			writer.Close ();
			stream.Close ();

			return output;
		}

		public byte[] EncryptData (XmlElement inputElement, SymmetricAlgorithm symAlg, bool content)
		{
			if (content)
				return EncryptData (Encoding.GetBytes (inputElement.InnerXml), symAlg);
			else
				return EncryptData (Encoding.GetBytes (inputElement.OuterXml), symAlg);
		}

		public static byte[] EncryptKey (byte[] keyData, SymmetricAlgorithm symAlg)
		{
			if (symAlg is TripleDES)
				return SymmetricKeyWrap.TripleDESKeyWrapEncrypt (symAlg.Key, keyData);
			if (symAlg is Rijndael)
				return SymmetricKeyWrap.AESKeyWrapEncrypt (symAlg.Key, keyData);

			throw new CryptographicException ("The specified cryptographic transform is not supported.");
		}

		[MonoTODO ("Test this.")]
		public static byte[] EncryptKey (byte[] keyData, RSA rsa, bool fOAEP)
		{
			AsymmetricKeyExchangeFormatter formatter = null;
			if (fOAEP) 
				formatter = new RSAOAEPKeyExchangeFormatter (rsa);
			else
				formatter = new RSAPKCS1KeyExchangeFormatter (rsa);
			return formatter.CreateKeyExchange (keyData);
		}

		private static SymmetricAlgorithm GetAlgorithm (string symAlgUri)
		{
			SymmetricAlgorithm symAlg = null;

			switch (symAlgUri) {
			case XmlEncAES128Url:
			case XmlEncAES128KeyWrapUrl:
				symAlg = SymmetricAlgorithm.Create ("Rijndael");
				symAlg.KeySize = 128;
				break;
			case XmlEncAES192Url:
			case XmlEncAES192KeyWrapUrl:
				symAlg = SymmetricAlgorithm.Create ("Rijndael");
				symAlg.KeySize = 192;
				break;
			case XmlEncAES256Url:
			case XmlEncAES256KeyWrapUrl:
				symAlg = SymmetricAlgorithm.Create ("Rijndael");
				symAlg.KeySize = 256;
				break;
			case XmlEncDESUrl:
				symAlg = SymmetricAlgorithm.Create ("DES");
				break;
			case XmlEncTripleDESUrl:
			case XmlEncTripleDESKeyWrapUrl:
				symAlg = SymmetricAlgorithm.Create ("TripleDES");
				break;
			default:
				throw new ArgumentException ("symAlgUri");
			}

			return symAlg;
		}

		private static string GetAlgorithmUri (SymmetricAlgorithm symAlg)
		{
			if (symAlg is Rijndael)
			{
				switch (symAlg.KeySize) {
				case 128:
					return XmlEncAES128Url;
				case 192:
					return XmlEncAES192Url;
				case 256:
					return XmlEncAES256Url;
				}
			}
			else if (symAlg is DES)
				return XmlEncDESUrl;
			else if (symAlg is TripleDES)
				return XmlEncTripleDESUrl;

			throw new ArgumentException ("symAlg");
		}

		private static string GetKeyWrapAlgorithmUri (object keyAlg)
		{
			if (keyAlg is Rijndael)
			{
				switch (((Rijndael) keyAlg).KeySize) {
				case 128:
					return XmlEncAES128KeyWrapUrl;
				case 192:
					return XmlEncAES192KeyWrapUrl;
				case 256:
					return XmlEncAES256KeyWrapUrl;
				}
			}
			else if (keyAlg is RSA) 
				return XmlEncRSA15Url;
			else if (keyAlg is TripleDES)
				return XmlEncTripleDESKeyWrapUrl;

			throw new ArgumentException ("keyAlg");
		}

		public virtual byte[] GetDecryptionIV (EncryptedData encryptedData, string symAlgUri)
		{
			SymmetricAlgorithm symAlg = GetAlgorithm (symAlgUri);
			byte[] iv = new Byte [symAlg.BlockSize / 8];
			Buffer.BlockCopy (encryptedData.CipherData.CipherValue, 0, iv, 0, iv.Length);
			return iv;
		}

		public virtual SymmetricAlgorithm GetDecryptionKey (EncryptedData encryptedData, string symAlgUri)
		{
			SymmetricAlgorithm symAlg = GetAlgorithm (symAlgUri);
			symAlg.IV = GetDecryptionIV (encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm);
			KeyInfo keyInfo = encryptedData.KeyInfo;
			foreach (KeyInfoClause clause in keyInfo) {
				if (clause is KeyInfoEncryptedKey) {
					symAlg.Key = DecryptEncryptedKey (((KeyInfoEncryptedKey) clause).EncryptedKey);
					break;
				}
			}
			return symAlg;
		}

		public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
		{
                        // this works only if there's a DTD or XSD available to define the ID
			XmlElement xel = document.GetElementById (idValue);
			if (xel == null) {
				// search an "undefined" ID
				xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
			}
			return xel;
		}

		public void ReplaceData (XmlElement inputElement, byte[] decryptedData)
		{
			XmlDocument ownerDocument = inputElement.OwnerDocument;
			XmlTextReader reader = new XmlTextReader (new StringReader (Encoding.GetString (decryptedData, 0, decryptedData.Length)));
			reader.MoveToContent ();
			XmlNode node = ownerDocument.ReadNode (reader);
			inputElement.ParentNode.ReplaceChild (node, inputElement);
		}

		public static void ReplaceElement (XmlElement inputElement, EncryptedData encryptedData, bool content)
		{
			XmlDocument ownerDocument = inputElement.OwnerDocument;
			inputElement.ParentNode.ReplaceChild (encryptedData.GetXml (ownerDocument), inputElement);
		}

		private byte[] Transform (byte[] data, ICryptoTransform transform)
		{
			return Transform (data, transform, 0, false);
		}

		private byte[] Transform (byte[] data, ICryptoTransform transform, int blockOctetCount, bool trimPadding)
		{
			MemoryStream output = new MemoryStream ();
			CryptoStream crypto = new CryptoStream (output, transform, CryptoStreamMode.Write);
			crypto.Write (data, 0, data.Length);

			crypto.FlushFinalBlock ();

			// strip padding (see xmlenc spec 5.2)
			int trimSize = 0;
			if (trimPadding)
				trimSize = output.GetBuffer () [output.Length - 1];
			// It should not happen, but somehow .NET allows such cipher 
			// data as if there were no padding.
			if (trimSize > blockOctetCount)
				trimSize = 0;
			byte[] result = new byte [output.Length - blockOctetCount - trimSize];
			Array.Copy (output.GetBuffer (), blockOctetCount, result, 0, result.Length);

			crypto.Close ();
			output.Close ();

			return result;
		}

		#endregion // Methods
	}
}

#endif