New test.
[mono.git] / mcs / class / corlib / System.Security.Policy / Hash.cs
1 //
2 // System.Security.Policy.Hash
3 //
4 // Authors:
5 //      Jackson Harper (Jackson@LatitudeGeo.com)
6 //      Sebastien Pouliot  <sebastien@ximian.com>
7 //
8 // (C) 2002 Jackson Harper, All rights reserved.
9 // Portions (C) 2002 Motus Technologies Inc. (http://www.motus.com)
10 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 using System.IO;
33 using System.Reflection;
34 using System.Runtime.InteropServices;
35 using System.Runtime.Serialization;
36 using System.Security.Cryptography;
37 using System.Security.Permissions;
38 using System.Text;
39
40 namespace System.Security.Policy {
41
42 [Serializable]
43 #if NET_2_0
44 [ComVisible (true)]
45 #else
46 [MonoTODO ("(1.x) This doesn't match the MS version perfectly.")]
47 // but it does seems to works exactly like Fx 2.0 beta 1 (and beta2 too) !?!?!
48 #endif
49 public sealed class Hash : ISerializable, IBuiltInEvidence {
50
51         private Assembly assembly;
52         private byte[] data;
53
54         internal byte[] _md5;
55         internal byte[] _sha1;
56
57         public Hash (Assembly assembly) 
58         {
59                 if (assembly == null)
60                         throw new ArgumentNullException ("assembly");
61                 this.assembly = assembly;
62         }
63
64         internal Hash () 
65         {
66         }
67
68         internal Hash (SerializationInfo info, StreamingContext context)
69         {
70                 data = (byte[]) info.GetValue ("RawData", typeof (byte[]));
71         }
72
73         //
74         // Public Properties
75         //
76
77         public byte[] MD5 {
78                 get {
79                         // Case 1: we have a MD5 value - either precalculated or static (FX 2.0)
80                         if (_md5 != null)
81                                 return _md5;
82
83                         // Case 2: we don't have a MD5 value precalculated so we either
84                         // (a): have an assembly reference - and can calculate the hash; or
85                         // (b): have been initialized with a static MD5 value (FX 2.0)
86 #if NET_2_0
87                         if ((assembly == null) && (_sha1 != null)) {
88                                 string msg = Locale.GetText ("No assembly data. This instance was initialized with an MSHA1 digest value.");
89                                 throw new SecurityException (msg);
90                         }
91 #endif
92                         // fully named to avoid conflit between MD5 property and class name
93                         HashAlgorithm hash = System.Security.Cryptography.MD5.Create ();
94                         _md5 = GenerateHash (hash);
95                         return _md5;
96                 }
97         }
98
99         public byte[] SHA1 {
100                 get {
101                         // Case 1: we have a SHA1 value - either precalculated or static (FX 2.0)
102                         if (_sha1 != null)
103                                 return _sha1;
104                         
105                         // Case 2: we don't have a SHA1 value precalculated so we either
106                         // (a): have an assembly reference - and can calculate the hash; or
107                         // (b): have been initialized with a static MD5 value (FX 2.0)
108 #if NET_2_0
109                         if ((assembly == null) && (_md5 != null)) {
110                                 string msg = Locale.GetText ("No assembly data. This instance was initialized with an MD5 digest value.");
111                                 throw new SecurityException (msg);
112                         }
113 #endif
114                         // fully named to avoid conflit between SHA1 property and class name
115                         HashAlgorithm hash = System.Security.Cryptography.SHA1.Create ();
116                         _sha1 = GenerateHash (hash);
117                         return _sha1;
118                 }
119         }
120
121         //
122         // Public Methods
123         //
124
125         public byte[] GenerateHash (HashAlgorithm hashAlg) 
126         {
127                 if (hashAlg == null)
128                         throw new ArgumentNullException ("hashAlg");
129                 return hashAlg.ComputeHash (GetData ());
130         }
131
132         public void GetObjectData (SerializationInfo info, StreamingContext context) 
133         {
134                 if (info == null)
135                         throw new ArgumentNullException ("info");
136                 info.AddValue ("RawData", GetData ());
137         }
138
139         public override string ToString () 
140         {
141                 SecurityElement se = new SecurityElement (GetType ().FullName);
142                 se.AddAttribute ("version", "1");
143                 
144                 StringBuilder sb = new StringBuilder ();
145                 byte[] raw = GetData ();
146                 for (int i=0; i < raw.Length; i++)
147                         sb.Append (raw [i].ToString ("X2"));
148
149                 se.AddChild (new SecurityElement ("RawData", sb.ToString ()));
150                 return se.ToString ();
151         }
152
153         //
154         // Private Methods
155         //
156
157         // FIXME: be more restrictive when imperative security is implemented
158         [FileIOPermission (SecurityAction.Assert, Unrestricted = true)]
159         private byte[] GetData () 
160         {
161 #if NET_2_0
162                 if ((assembly == null) && (data == null)) {
163                         string msg = Locale.GetText ("No assembly data.");
164                         throw new SecurityException (msg);
165                 }
166 #endif
167                 if (null == data) {
168                         // TODO (Pre-Fx-2.0) we mustn't hash the complete assembly!
169                         // ---- Look at ToString (MS version) for what to hash (and what not to)
170                         // TODO we must drop the authenticode signature (if present)
171                         FileStream stream = new 
172                                 FileStream (assembly.Location, FileMode.Open, FileAccess.Read);
173                         data = new byte [stream.Length];
174                         stream.Read (data, 0, (int)stream.Length);
175                 }
176
177                 return data;
178         }
179
180         // interface IBuiltInEvidence
181
182         int IBuiltInEvidence.GetRequiredSize (bool verbose) 
183         {
184                 return (verbose ? 5 : 0);       // as documented
185         }
186
187         [MonoTODO ("IBuiltInEvidence")]
188         int IBuiltInEvidence.InitFromBuffer (char [] buffer, int position) 
189         {
190                 return 0;
191         }
192
193         [MonoTODO ("IBuiltInEvidence")]
194         int IBuiltInEvidence.OutputToBuffer (char [] buffer, int position, bool verbose) 
195         {
196                 return 0;
197         }
198
199 #if NET_2_0
200         static public Hash CreateMD5 (byte[] md5)
201         {
202                 if (md5 == null)
203                         throw new ArgumentNullException ("md5");
204                 Hash h = new Hash ();
205                 h._md5 = md5;
206                 return h;
207         }
208
209         static public Hash CreateSHA1 (byte[] sha1)
210         {
211                 if (sha1 == null)
212                         throw new ArgumentNullException ("sha1");
213                 Hash h = new Hash ();
214                 h._sha1 = sha1;
215                 return h;
216         }
217 #endif
218 }
219
220 }