Remove duplicated files from system.dll (saves about 100kb)
[mono.git] / mcs / class / System / System.Security.Cryptography.X509Certificates / X509Certificate2Collection.cs
1 //
2 // System.Security.Cryptography.X509Certificates.X509Certificate2Collection class
3 //
4 // Authors:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //      Tim Coleman (tim@timcoleman.com)
7 //
8 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Copyright (C) Tim Coleman, 2004
10 // Copyright (C) 2005, 2006 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 #if SECURITY_DEP
33
34 using System.Collections;
35 using System.Globalization;
36
37 namespace System.Security.Cryptography.X509Certificates {
38
39         public class X509Certificate2Collection : X509CertificateCollection {
40
41                 // constructors
42
43                 public X509Certificate2Collection ()
44                 {
45                 }
46
47                 public X509Certificate2Collection (X509Certificate2Collection certificates)
48                 {
49                         AddRange (certificates);
50                 }
51
52                 public X509Certificate2Collection (X509Certificate2 certificate) 
53                 {
54                         Add (certificate);
55                 }
56
57                 public X509Certificate2Collection (X509Certificate2[] certificates) 
58                 {
59                         AddRange (certificates);
60                 }
61
62                 // properties
63
64                 public new X509Certificate2 this [int index] {
65                         get {
66                                 if (index < 0)
67                                         throw new ArgumentOutOfRangeException ("negative index");
68                                 if (index >= InnerList.Count)
69                                         throw new ArgumentOutOfRangeException ("index >= Count");
70                                 return (X509Certificate2) InnerList [index];
71                         }
72                         set { InnerList [index] = value; }
73                 }
74
75                 // methods
76
77                 public int Add (X509Certificate2 certificate)
78                 {
79                         if (certificate == null)
80                                 throw new ArgumentNullException ("certificate");
81
82                         return InnerList.Add (certificate);
83                 }
84
85                 [MonoTODO ("Method isn't transactional (like documented)")]
86                 public void AddRange (X509Certificate2[] certificates) 
87                 {
88                         if (certificates == null)
89                                 throw new ArgumentNullException ("certificates");
90
91                         for (int i=0; i < certificates.Length; i++)
92                                 InnerList.Add (certificates [i]);
93                 }
94
95                 [MonoTODO ("Method isn't transactional (like documented)")]
96                 public void AddRange (X509Certificate2Collection certificates) 
97                 {
98                         if (certificates == null)
99                                 throw new ArgumentNullException ("certificates");
100
101                         InnerList.AddRange (certificates);
102                 }
103
104                 public bool Contains (X509Certificate2 certificate) 
105                 {
106                         if (certificate == null)
107                                 throw new ArgumentNullException ("certificate");
108
109                         foreach (X509Certificate2 c in InnerList) {
110                                 if (c.Equals (certificate))
111                                         return true;
112                         }
113                         return false;
114                 }
115
116                 [MonoTODO ("only support X509ContentType.Cert")]
117                 public byte[] Export (X509ContentType contentType) 
118                 {
119                         return Export (contentType, null);
120                 }
121
122                 [MonoTODO ("only support X509ContentType.Cert")]
123                 public byte[] Export (X509ContentType contentType, string password) 
124                 {
125                         switch (contentType) {
126                         case X509ContentType.Cert:
127                         case X509ContentType.Pfx: // this includes Pkcs12
128                         case X509ContentType.SerializedCert:
129                                 // if multiple certificates are present we only export the last one
130                                 if (Count > 0)
131                                         return this [Count - 1].Export (contentType, password);
132                                 break;
133                         case X509ContentType.Pkcs7:
134                                 // TODO
135                                 break;
136                         case X509ContentType.SerializedStore:
137                                 // TODO
138                                 break;
139                         default:
140                                 // this includes Authenticode, Unknown and bad values
141                                 string msg = Locale.GetText ("Cannot export certificate(s) to the '{0}' format", contentType);
142                                 throw new CryptographicException (msg);
143                         }
144                         return null;
145                 }
146
147                 static string[] newline_split = new string[] { Environment.NewLine };
148                 
149                 [MonoTODO ("Does not support X509FindType.FindByTemplateName, FindByApplicationPolicy and FindByCertificatePolicy")]
150                 public X509Certificate2Collection Find (X509FindType findType, object findValue, bool validOnly) 
151                 {
152                         if (findValue == null)
153                                 throw new ArgumentNullException ("findValue");
154
155                         string str = String.Empty;
156                         string oid = String.Empty;
157                         X509KeyUsageFlags ku = X509KeyUsageFlags.None;
158                         DateTime dt = DateTime.MinValue;
159
160                         switch (findType) {
161                         case X509FindType.FindByThumbprint:
162                         case X509FindType.FindBySubjectName:
163                         case X509FindType.FindBySubjectDistinguishedName:
164                         case X509FindType.FindByIssuerName:
165                         case X509FindType.FindByIssuerDistinguishedName:
166                         case X509FindType.FindBySerialNumber:
167                         case X509FindType.FindByTemplateName:
168                         case X509FindType.FindBySubjectKeyIdentifier:
169                                 try {
170                                         str = (string) findValue;
171                                 }
172                                 catch (Exception e) {
173                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
174                                                 findValue.GetType (), "string");
175                                         throw new CryptographicException (msg, e);
176                                 }
177                                 break;
178                         case X509FindType.FindByApplicationPolicy:
179                         case X509FindType.FindByCertificatePolicy:
180                         case X509FindType.FindByExtension:
181                                 try {
182                                         oid = (string) findValue;
183                                 }
184                                 catch (Exception e) {
185                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
186                                                 findValue.GetType (), "X509KeyUsageFlags");
187                                         throw new CryptographicException (msg, e);
188                                 }
189                                 // OID validation
190                                 try {
191                                         CryptoConfig.EncodeOID (oid);
192                                 }
193                                 catch (CryptographicUnexpectedOperationException) {
194                                         string msg = Locale.GetText ("Invalid OID value '{0}'.", oid);
195                                         throw new ArgumentException ("findValue", msg);
196                                 }
197                                 break;
198                         case X509FindType.FindByKeyUsage:
199                                 try {
200                                         ku = (X509KeyUsageFlags) findValue;
201                                 }
202                                 catch (Exception e) {
203                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
204                                                 findValue.GetType (), "X509KeyUsageFlags");
205                                         throw new CryptographicException (msg, e);
206                                 }
207                                 break;
208                         case X509FindType.FindByTimeValid:
209                         case X509FindType.FindByTimeNotYetValid:
210                         case X509FindType.FindByTimeExpired:
211                                 try {
212                                         dt = (DateTime) findValue;
213                                 }
214                                 catch (Exception e) {
215                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
216                                                 findValue.GetType (), "X509DateTime");
217                                         throw new CryptographicException (msg,e );
218                                 }
219                                 break;
220                         default:
221                                 {
222                                         string msg = Locale.GetText ("Invalid find type '{0}'.", findType);
223                                         throw new CryptographicException (msg);
224                                 }
225                         }
226
227                         CultureInfo cinv = CultureInfo.InvariantCulture;
228                         X509Certificate2Collection results = new  X509Certificate2Collection ();
229                         foreach (X509Certificate2 x in InnerList) {
230                                 bool value_match = false;
231
232                                 switch (findType) {
233                                 case X509FindType.FindByThumbprint:
234                                         // works with Thumbprint, GetCertHashString in both normal (upper) and lower case
235                                         value_match = ((String.Compare (str, x.Thumbprint, true, cinv) == 0) ||
236                                                 (String.Compare (str, x.GetCertHashString (), true, cinv) == 0));
237                                         break;
238                                 case X509FindType.FindBySubjectName:
239                                         string [] names = x.SubjectName.Format (true).Split (newline_split, StringSplitOptions.RemoveEmptyEntries);
240                                         foreach (string name in names) {
241                                                 int pos = name.IndexOf ('=');
242                                                 value_match = (name.IndexOf (str, pos, StringComparison.InvariantCultureIgnoreCase) >= 0);
243                                                 if (value_match)
244                                                         break;
245                                         }
246                                         break;
247                                 case X509FindType.FindBySubjectDistinguishedName:
248                                         value_match = (String.Compare (str, x.Subject, true, cinv) == 0);
249                                         break;
250                                 case X509FindType.FindByIssuerName:
251                                         string iname = x.GetNameInfo (X509NameType.SimpleName, true);
252                                         value_match = (iname.IndexOf (str, StringComparison.InvariantCultureIgnoreCase) >= 0);
253                                         break;
254                                 case X509FindType.FindByIssuerDistinguishedName:
255                                         value_match = (String.Compare (str, x.Issuer, true, cinv) == 0);
256                                         break;
257                                 case X509FindType.FindBySerialNumber:
258                                         value_match = (String.Compare (str, x.SerialNumber, true, cinv) == 0);
259                                         break;
260                                 case X509FindType.FindByTemplateName:
261                                         // TODO - find a valid test case
262                                         break;
263                                 case X509FindType.FindBySubjectKeyIdentifier:
264                                         X509SubjectKeyIdentifierExtension ski = (x.Extensions ["2.5.29.14"] as X509SubjectKeyIdentifierExtension);
265                                         if (ski != null) {
266                                                 value_match = (String.Compare (str, ski.SubjectKeyIdentifier, true, cinv) == 0);
267                                         }
268                                         break;
269                                 case X509FindType.FindByApplicationPolicy:
270                                         // note: include when no extensions are present (even if v3)
271                                         value_match = (x.Extensions.Count == 0);
272                                         // TODO - find test case with extension
273                                         break;
274                                 case X509FindType.FindByCertificatePolicy:
275                                         // TODO - find test case with extension
276                                         break;
277                                 case X509FindType.FindByExtension:
278                                         value_match = (x.Extensions [oid] != null);
279                                         break;
280                                 case X509FindType.FindByKeyUsage:
281                                         X509KeyUsageExtension kue = (x.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
282                                         if (kue == null) {
283                                                 // key doesn't have any hard coded limitations
284                                                 // note: MS doesn't check for ExtendedKeyUsage
285                                                 value_match = true; 
286                                         } else {
287                                                 value_match = ((kue.KeyUsages & ku) == ku);
288                                         }
289                                         break;
290                                 case X509FindType.FindByTimeValid:
291                                         value_match = ((dt >= x.NotBefore) && (dt <= x.NotAfter));
292                                         break;
293                                 case X509FindType.FindByTimeNotYetValid:
294                                         value_match = (dt < x.NotBefore);
295                                         break;
296                                 case X509FindType.FindByTimeExpired:
297                                         value_match = (dt > x.NotAfter);
298                                         break;
299                                 }
300
301                                 if (!value_match)
302                                         continue;
303
304                                 if (validOnly) {
305                                         try {
306                                                 if (x.Verify ())
307                                                         results.Add (x);
308                                         }
309                                         catch {
310                                         }
311                                 } else {
312                                         results.Add (x);
313                                 }
314                         }
315                         return results;
316                 }
317
318                 public new X509Certificate2Enumerator GetEnumerator () 
319                 {
320                         return new X509Certificate2Enumerator (this);
321                 }
322
323                 [MonoTODO ("same limitations as X509Certificate2.Import")]
324                 public void Import (byte[] rawData) 
325                 {
326                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
327                         X509Certificate2 cert = new X509Certificate2 ();
328                         cert.Import (rawData);
329                         Add (cert);
330                 }
331
332                 [MonoTODO ("same limitations as X509Certificate2.Import")]
333                 public void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
334                 {
335                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
336                         X509Certificate2 cert = new X509Certificate2 ();
337                         cert.Import (rawData, password, keyStorageFlags);
338                         Add (cert);
339                 }
340
341                 [MonoTODO ("same limitations as X509Certificate2.Import")]
342                 public void Import (string fileName) 
343                 {
344                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
345                         X509Certificate2 cert = new X509Certificate2 ();
346                         cert.Import (fileName);
347                         Add (cert);
348                 }
349
350                 [MonoTODO ("same limitations as X509Certificate2.Import")]
351                 public void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags) 
352                 {
353                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
354                         X509Certificate2 cert = new X509Certificate2 ();
355                         cert.Import (fileName, password, keyStorageFlags);
356                         Add (cert);
357                 }
358
359                 public void Insert (int index, X509Certificate2 certificate) 
360                 {
361                         if (certificate == null)
362                                 throw new ArgumentNullException ("certificate");
363                         if (index < 0)
364                                 throw new ArgumentOutOfRangeException ("negative index");
365                         if (index >= InnerList.Count)
366                                 throw new ArgumentOutOfRangeException ("index >= Count");
367
368                         InnerList.Insert (index, certificate);
369                 }
370
371                 public void Remove (X509Certificate2 certificate) 
372                 {
373                         if (certificate == null)
374                                 throw new ArgumentNullException ("certificate");
375
376                         for (int i=0; i < InnerList.Count; i++) {
377                                 X509Certificate c = (X509Certificate) InnerList [i];
378                                 if (c.Equals (certificate)) {
379                                         InnerList.RemoveAt (i);
380                                         // only first instance is removed
381                                         return;
382                                 }
383                         }
384                 }
385
386                 [MonoTODO ("Method isn't transactional (like documented)")]
387                 public void RemoveRange (X509Certificate2[] certificates)
388                 {
389                         if (certificates == null)
390                                 throw new ArgumentNullException ("certificate");
391
392                         foreach (X509Certificate2 x in certificates)
393                                 Remove (x);
394                 }
395
396                 [MonoTODO ("Method isn't transactional (like documented)")]
397                 public void RemoveRange (X509Certificate2Collection certificates) 
398                 {
399                         if (certificates == null)
400                                 throw new ArgumentNullException ("certificate");
401
402                         foreach (X509Certificate2 x in certificates)
403                                 Remove (x);
404                 }
405         }
406 }
407
408 #endif