2 // CipherData.cs - CipherData implementation for XML Encryption
3 // http://www.w3.org/2001/04/xmlenc#sec-CipherData
6 // Tim Coleman (tim@timcoleman.com)
8 // Copyright (C) Tim Coleman, 2004
12 using System.Security.Cryptography;
16 namespace System.Security.Cryptography.Xml {
17 public sealed class CipherData {
22 CipherReference cipherReference;
32 public CipherData (byte[] cipherValue)
34 CipherValue = cipherValue;
37 public CipherData (CipherReference cipherReference)
39 CipherReference = cipherReference;
42 #endregion // Constructors
46 public CipherReference CipherReference {
47 get { return cipherReference; }
49 if (CipherValue != null)
50 throw new CryptographicException ("A Cipher Data element should have either a CipherValue or a CipherReference element.");
51 cipherReference = value;
55 public byte[] CipherValue {
56 get { return cipherValue; }
58 if (CipherReference != null)
59 throw new CryptographicException ("A Cipher Data element should have either a CipherValue or a CipherReference element.");
64 #endregion // Properties
68 public XmlElement GetXml ()
70 return GetXml (new XmlDocument ());
73 internal XmlElement GetXml (XmlDocument document)
75 if (CipherReference == null && CipherValue == null)
76 throw new CryptographicException ("A Cipher Data element should have either a CipherValue or a CipherReference element.");
78 XmlElement xel = document.CreateElement (XmlEncryption.ElementNames.CipherData, XmlEncryption.NamespaceURI);
79 if (CipherReference != null)
80 xel.AppendChild (document.ImportNode (cipherReference.GetXml (), true));
82 if (CipherValue != null) {
83 XmlElement xcv = document.CreateElement (XmlEncryption.ElementNames.CipherValue, XmlEncryption.NamespaceURI);
84 StreamReader reader = new StreamReader (new CryptoStream (new MemoryStream (cipherValue), new ToBase64Transform (), CryptoStreamMode.Read));
85 xcv.InnerText = reader.ReadToEnd ();
87 xel.AppendChild (xcv);
92 public void LoadXml (XmlElement value)
94 CipherReference = null;
98 throw new ArgumentNullException ("value");
100 if ((value.LocalName != XmlEncryption.ElementNames.CipherData) || (value.NamespaceURI != XmlEncryption.NamespaceURI))
101 throw new CryptographicException ("Malformed Cipher Data element.");
103 foreach (XmlNode n in value.ChildNodes) {
104 if (n is XmlWhitespace)
107 switch (n.LocalName) {
108 case XmlEncryption.ElementNames.CipherReference:
109 cipherReference = new CipherReference ();
110 cipherReference.LoadXml ((XmlElement) n);
112 case XmlEncryption.ElementNames.CipherValue:
113 CipherValue = Convert.FromBase64String (n.InnerText);
118 if (CipherReference == null && CipherValue == null)
119 throw new CryptographicException ("A Cipher Data element should have either a CipherValue or a CipherReference element.");
123 #endregion // Methods