2 // EncryptedXml.cs - EncryptedXml implementation for XML Encryption
5 // Tim Coleman (tim@timcoleman.com)
7 // Copyright (C) Tim Coleman, 2004
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
32 using System.Collections;
34 using System.Security.Cryptography;
35 using System.Security.Cryptography.X509Certificates;
36 using System.Security.Policy;
40 namespace System.Security.Cryptography.Xml {
41 public class EncryptedXml {
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";
63 Evidence documentEvidence;
64 Encoding encoding = Encoding.UTF8;
65 internal Hashtable keyNameMapping = new Hashtable ();
66 CipherMode mode = CipherMode.CBC;
67 PaddingMode padding = PaddingMode.ISO10126;
77 public EncryptedXml ()
82 public EncryptedXml (XmlDocument document)
84 this.document = document;
88 public EncryptedXml (XmlDocument document, Evidence evidence)
90 this.document = document;
91 DocumentEvidence = evidence;
94 #endregion // Constructors
98 public Evidence DocumentEvidence {
99 get { return documentEvidence; }
100 set { documentEvidence = value; }
103 public Encoding Encoding {
104 get { return encoding; }
105 set { encoding = value; }
108 public CipherMode Mode {
110 set { mode = value; }
113 public PaddingMode Padding {
114 get { return padding; }
115 set { padding = value; }
118 public string Recipient {
119 get { return recipient; }
120 set { recipient = value; }
123 public XmlResolver Resolver {
124 get { return resolver; }
125 set { resolver = value; }
128 #endregion // Properties
132 public void AddKeyNameMapping (string keyName, object keyObject)
134 keyNameMapping [keyName] = keyObject;
137 public void ClearKeyNameMappings ()
139 keyNameMapping.Clear ();
142 public byte[] DecryptData (EncryptedData encryptedData, SymmetricAlgorithm symAlg)
144 return Transform (encryptedData.CipherData.CipherValue, symAlg.CreateDecryptor (), symAlg.BlockSize / 8);
147 public void DecryptDocument ()
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));
158 public virtual byte[] DecryptEncryptedKey (EncryptedKey encryptedKey)
160 object keyAlg = null;
161 foreach (KeyInfoClause innerClause in encryptedKey.KeyInfo) {
162 if (innerClause is KeyInfoName) {
163 keyAlg = keyNameMapping [((KeyInfoName) innerClause).Value];
167 switch (encryptedKey.EncryptionMethod.KeyAlgorithm) {
169 return DecryptKey (encryptedKey.CipherData.CipherValue, (RSA) keyAlg, false);
170 case XmlEncRSAOAEPUrl:
171 return DecryptKey (encryptedKey.CipherData.CipherValue, (RSA) keyAlg, true);
173 return DecryptKey (encryptedKey.CipherData.CipherValue, (SymmetricAlgorithm) keyAlg);
176 public static byte[] DecryptKey (byte[] keyData, SymmetricAlgorithm symAlg)
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.");
185 [MonoTODO ("Test this.")]
186 public static byte[] DecryptKey (byte[] keyData, RSA rsa, bool fOAEP)
188 AsymmetricKeyExchangeDeformatter deformatter = null;
190 deformatter = new RSAOAEPKeyExchangeDeformatter (rsa);
192 deformatter = new RSAPKCS1KeyExchangeDeformatter (rsa);
193 return deformatter.DecryptKeyExchange (keyData);
196 public EncryptedData Encrypt (XmlElement inputElement, string keyName)
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.
204 SymmetricAlgorithm symAlg = SymmetricAlgorithm.Create ("Rijndael");
205 symAlg.KeySize = 256;
206 symAlg.GenerateKey ();
207 symAlg.GenerateIV ();
209 EncryptedData encryptedData = new EncryptedData ();
210 EncryptedKey encryptedKey = new EncryptedKey();
212 object keyAlg = keyNameMapping [keyName];
214 encryptedKey.EncryptionMethod = new EncryptionMethod (GetKeyWrapAlgorithmUri (keyAlg));
217 encryptedKey.CipherData = new CipherData (EncryptKey (symAlg.Key, (RSA) keyAlg, false));
219 encryptedKey.CipherData = new CipherData (EncryptKey (symAlg.Key, (SymmetricAlgorithm) keyAlg));
221 encryptedKey.KeyInfo = new KeyInfo();
222 encryptedKey.KeyInfo.AddClause (new KeyInfoName (keyName));
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));
230 return encryptedData;
234 public EncryptedData Encrypt (XmlElement inputElement, X509Certificate2 certificate)
236 throw new NotImplementedException ();
239 public byte[] EncryptData (byte[] plainText, SymmetricAlgorithm symAlg)
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);
246 writer.Write (symAlg.IV);
247 writer.Write (Transform (plainText, symAlg.CreateEncryptor ()));
250 byte [] output = stream.ToArray ();
258 public byte[] EncryptData (XmlElement inputElement, SymmetricAlgorithm symAlg, bool content)
261 return EncryptData (Encoding.GetBytes (inputElement.InnerXml), symAlg);
263 return EncryptData (Encoding.GetBytes (inputElement.OuterXml), symAlg);
266 public static byte[] EncryptKey (byte[] keyData, SymmetricAlgorithm symAlg)
268 if (symAlg is TripleDES)
269 return SymmetricKeyWrap.TripleDESKeyWrapEncrypt (symAlg.Key, keyData);
270 if (symAlg is Rijndael)
271 return SymmetricKeyWrap.AESKeyWrapEncrypt (symAlg.Key, keyData);
273 throw new CryptographicException ("The specified cryptographic transform is not supported.");
276 [MonoTODO ("Test this.")]
277 public static byte[] EncryptKey (byte[] keyData, RSA rsa, bool fOAEP)
279 AsymmetricKeyExchangeFormatter formatter = null;
281 formatter = new RSAOAEPKeyExchangeFormatter (rsa);
283 formatter = new RSAPKCS1KeyExchangeFormatter (rsa);
284 return formatter.CreateKeyExchange (keyData);
287 private static SymmetricAlgorithm GetAlgorithm (string symAlgUri)
289 SymmetricAlgorithm symAlg = null;
292 case XmlEncAES128Url:
293 case XmlEncAES128KeyWrapUrl:
294 symAlg = SymmetricAlgorithm.Create ("Rijndael");
295 symAlg.KeySize = 128;
297 case XmlEncAES192Url:
298 case XmlEncAES192KeyWrapUrl:
299 symAlg = SymmetricAlgorithm.Create ("Rijndael");
300 symAlg.KeySize = 192;
302 case XmlEncAES256Url:
303 case XmlEncAES256KeyWrapUrl:
304 symAlg = SymmetricAlgorithm.Create ("Rijndael");
305 symAlg.KeySize = 256;
308 symAlg = SymmetricAlgorithm.Create ("DES");
310 case XmlEncTripleDESUrl:
311 case XmlEncTripleDESKeyWrapUrl:
312 symAlg = SymmetricAlgorithm.Create ("TripleDES");
315 throw new ArgumentException ("symAlgUri");
321 private static string GetAlgorithmUri (SymmetricAlgorithm symAlg)
323 if (symAlg is Rijndael)
325 switch (symAlg.KeySize) {
327 return XmlEncAES128Url;
329 return XmlEncAES192Url;
331 return XmlEncAES256Url;
334 else if (symAlg is DES)
336 else if (symAlg is TripleDES)
337 return XmlEncTripleDESUrl;
339 throw new ArgumentException ("symAlg");
342 private static string GetKeyWrapAlgorithmUri (object keyAlg)
344 if (keyAlg is Rijndael)
346 switch (((Rijndael) keyAlg).KeySize) {
348 return XmlEncAES128KeyWrapUrl;
350 return XmlEncAES192KeyWrapUrl;
352 return XmlEncAES256KeyWrapUrl;
355 else if (keyAlg is RSA)
356 return XmlEncRSA15Url;
357 else if (keyAlg is TripleDES)
358 return XmlEncTripleDESKeyWrapUrl;
360 throw new ArgumentException ("keyAlg");
363 public virtual byte[] GetDecryptionIV (EncryptedData encryptedData, string symAlgUri)
365 SymmetricAlgorithm symAlg = GetAlgorithm (symAlgUri);
366 byte[] iv = new Byte [symAlg.BlockSize / 8];
367 Buffer.BlockCopy (encryptedData.CipherData.CipherValue, 0, iv, 0, iv.Length);
371 public virtual SymmetricAlgorithm GetDecryptionKey (EncryptedData encryptedData, string symAlgUri)
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);
385 public virtual XmlElement GetIdElement (XmlDocument document, string idValue)
387 // this works only if there's a DTD or XSD available to define the ID
388 XmlElement xel = document.GetElementById (idValue);
390 // search an "undefined" ID
391 xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']");
396 public void ReplaceData (XmlElement inputElement, byte[] decryptedData)
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);
405 public static void ReplaceElement (XmlElement inputElement, EncryptedData encryptedData, bool content)
407 XmlDocument ownerDocument = inputElement.OwnerDocument;
408 inputElement.ParentNode.ReplaceChild (encryptedData.GetXml (ownerDocument), inputElement);
411 private byte[] Transform (byte[] data, ICryptoTransform transform)
413 return Transform (data, transform, 0);
416 private byte[] Transform (byte[] data, ICryptoTransform transform, int startIndex)
418 MemoryStream output = new MemoryStream ();
419 CryptoStream crypto = new CryptoStream (output, transform, CryptoStreamMode.Write);
420 crypto.Write (data, startIndex, data.Length - startIndex);
422 crypto.FlushFinalBlock ();
424 byte[] result = output.ToArray ();
432 #endregion // Methods