2008-06-26 Sebastien Pouliot <sebastien@ximian.com>
[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 NET_2_0 && 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                 [MonoTODO ("Does not support X509FindType.FindByTemplateName, FindByApplicationPolicy and FindByCertificatePolicy")]
148                 public X509Certificate2Collection Find (X509FindType findType, object findValue, bool validOnly) 
149                 {
150                         if (findValue == null)
151                                 throw new ArgumentNullException ("findValue");
152
153                         string str = String.Empty;
154                         string oid = String.Empty;
155                         X509KeyUsageFlags ku = X509KeyUsageFlags.None;
156                         DateTime dt = DateTime.MinValue;
157
158                         switch (findType) {
159                         case X509FindType.FindByThumbprint:
160                         case X509FindType.FindBySubjectName:
161                         case X509FindType.FindBySubjectDistinguishedName:
162                         case X509FindType.FindByIssuerName:
163                         case X509FindType.FindByIssuerDistinguishedName:
164                         case X509FindType.FindBySerialNumber:
165                         case X509FindType.FindByTemplateName:
166                         case X509FindType.FindBySubjectKeyIdentifier:
167                                 try {
168                                         str = (string) findValue;
169                                 }
170                                 catch (Exception e) {
171                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
172                                                 findValue.GetType (), "string");
173                                         throw new CryptographicException (msg, e);
174                                 }
175                                 break;
176                         case X509FindType.FindByApplicationPolicy:
177                         case X509FindType.FindByCertificatePolicy:
178                         case X509FindType.FindByExtension:
179                                 try {
180                                         oid = (string) findValue;
181                                 }
182                                 catch (Exception e) {
183                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
184                                                 findValue.GetType (), "X509KeyUsageFlags");
185                                         throw new CryptographicException (msg, e);
186                                 }
187                                 // OID validation
188                                 try {
189                                         CryptoConfig.EncodeOID (oid);
190                                 }
191                                 catch (CryptographicUnexpectedOperationException) {
192                                         string msg = Locale.GetText ("Invalid OID value '{0}'.", oid);
193                                         throw new ArgumentException ("findValue", msg);
194                                 }
195                                 break;
196                         case X509FindType.FindByKeyUsage:
197                                 try {
198                                         ku = (X509KeyUsageFlags) findValue;
199                                 }
200                                 catch (Exception e) {
201                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
202                                                 findValue.GetType (), "X509KeyUsageFlags");
203                                         throw new CryptographicException (msg, e);
204                                 }
205                                 break;
206                         case X509FindType.FindByTimeValid:
207                         case X509FindType.FindByTimeNotYetValid:
208                         case X509FindType.FindByTimeExpired:
209                                 try {
210                                         dt = (DateTime) findValue;
211                                 }
212                                 catch (Exception e) {
213                                         string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.", 
214                                                 findValue.GetType (), "X509DateTime");
215                                         throw new CryptographicException (msg,e );
216                                 }
217                                 break;
218                         default:
219                                 string msg = Locale.GetText ("Invalid find type '{0}'.", findType);
220                                 throw new CryptographicException (msg);
221                         }
222
223                         CultureInfo cinv = CultureInfo.InvariantCulture;
224                         X509Certificate2Collection results = new  X509Certificate2Collection ();
225                         foreach (X509Certificate2 x in InnerList) {
226                                 bool value_match = false;
227
228                                 switch (findType) {
229                                 case X509FindType.FindByThumbprint:
230                                         // works with Thumbprint, GetCertHashString in both normal (upper) and lower case
231                                         value_match = ((String.Compare (str, x.Thumbprint, true, cinv) == 0) ||
232                                                 (String.Compare (str, x.GetCertHashString (), true, cinv) == 0));
233                                         break;
234                                 case X509FindType.FindBySubjectName:
235                                         string sname = x.GetNameInfo (X509NameType.SimpleName, false);
236                                         value_match = (sname.IndexOf (str, StringComparison.InvariantCultureIgnoreCase) >= 0);
237                                         break;
238                                 case X509FindType.FindBySubjectDistinguishedName:
239                                         value_match = (String.Compare (str, x.Subject, true, cinv) == 0);
240                                         break;
241                                 case X509FindType.FindByIssuerName:
242                                         string iname = x.GetNameInfo (X509NameType.SimpleName, true);
243                                         value_match = (iname.IndexOf (str, StringComparison.InvariantCultureIgnoreCase) >= 0);
244                                         break;
245                                 case X509FindType.FindByIssuerDistinguishedName:
246                                         value_match = (String.Compare (str, x.Issuer, true, cinv) == 0);
247                                         break;
248                                 case X509FindType.FindBySerialNumber:
249                                         value_match = (String.Compare (str, x.SerialNumber, true, cinv) == 0);
250                                         break;
251                                 case X509FindType.FindByTemplateName:
252                                         // TODO - find a valid test case
253                                         break;
254                                 case X509FindType.FindBySubjectKeyIdentifier:
255                                         X509SubjectKeyIdentifierExtension ski = (x.Extensions ["2.5.29.14"] as X509SubjectKeyIdentifierExtension);
256                                         if (ski != null) {
257                                                 value_match = (String.Compare (str, ski.SubjectKeyIdentifier, true, cinv) == 0);
258                                         }
259                                         break;
260                                 case X509FindType.FindByApplicationPolicy:
261                                         // note: include when no extensions are present (even if v3)
262                                         value_match = (x.Extensions.Count == 0);
263                                         // TODO - find test case with extension
264                                         break;
265                                 case X509FindType.FindByCertificatePolicy:
266                                         // TODO - find test case with extension
267                                         break;
268                                 case X509FindType.FindByExtension:
269                                         value_match = (x.Extensions [oid] != null);
270                                         break;
271                                 case X509FindType.FindByKeyUsage:
272                                         X509KeyUsageExtension kue = (x.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
273                                         if (kue == null) {
274                                                 // key doesn't have any hard coded limitations
275                                                 // note: MS doesn't check for ExtendedKeyUsage
276                                                 value_match = true; 
277                                         } else {
278                                                 value_match = ((kue.KeyUsages & ku) == ku);
279                                         }
280                                         break;
281                                 case X509FindType.FindByTimeValid:
282                                         value_match = ((dt >= x.NotBefore) && (dt <= x.NotAfter));
283                                         break;
284                                 case X509FindType.FindByTimeNotYetValid:
285                                         value_match = (dt < x.NotBefore);
286                                         break;
287                                 case X509FindType.FindByTimeExpired:
288                                         value_match = (dt > x.NotAfter);
289                                         break;
290                                 }
291
292                                 if (!value_match)
293                                         continue;
294
295                                 if (validOnly) {
296                                         try {
297                                                 if (x.Verify ())
298                                                         results.Add (x);
299                                         }
300                                         catch {
301                                         }
302                                 } else {
303                                         results.Add (x);
304                                 }
305                         }
306                         return results;
307                 }
308
309                 public new X509Certificate2Enumerator GetEnumerator () 
310                 {
311                         return new X509Certificate2Enumerator (this);
312                 }
313
314                 [MonoTODO ("same limitations as X509Certificate2.Import")]
315                 public void Import (byte[] rawData) 
316                 {
317                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
318                         X509Certificate2 cert = new X509Certificate2 ();
319                         cert.Import (rawData);
320                         Add (cert);
321                 }
322
323                 [MonoTODO ("same limitations as X509Certificate2.Import")]
324                 public void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
325                 {
326                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
327                         X509Certificate2 cert = new X509Certificate2 ();
328                         cert.Import (rawData, password, keyStorageFlags);
329                         Add (cert);
330                 }
331
332                 [MonoTODO ("same limitations as X509Certificate2.Import")]
333                 public void Import (string fileName) 
334                 {
335                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
336                         X509Certificate2 cert = new X509Certificate2 ();
337                         cert.Import (fileName);
338                         Add (cert);
339                 }
340
341                 [MonoTODO ("same limitations as X509Certificate2.Import")]
342                 public void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags) 
343                 {
344                         // FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
345                         X509Certificate2 cert = new X509Certificate2 ();
346                         cert.Import (fileName, password, keyStorageFlags);
347                         Add (cert);
348                 }
349
350                 public void Insert (int index, X509Certificate2 certificate) 
351                 {
352                         if (certificate == null)
353                                 throw new ArgumentNullException ("certificate");
354                         if (index < 0)
355                                 throw new ArgumentOutOfRangeException ("negative index");
356                         if (index >= InnerList.Count)
357                                 throw new ArgumentOutOfRangeException ("index >= Count");
358
359                         InnerList.Insert (index, certificate);
360                 }
361
362                 public void Remove (X509Certificate2 certificate) 
363                 {
364                         if (certificate == null)
365                                 throw new ArgumentNullException ("certificate");
366
367                         for (int i=0; i < InnerList.Count; i++) {
368                                 X509Certificate c = (X509Certificate) InnerList [i];
369                                 if (c.Equals (certificate)) {
370                                         InnerList.RemoveAt (i);
371                                         // only first instance is removed
372                                         return;
373                                 }
374                         }
375                 }
376
377                 [MonoTODO ("Method isn't transactional (like documented)")]
378                 public void RemoveRange (X509Certificate2[] certificates)
379                 {
380                         if (certificates == null)
381                                 throw new ArgumentNullException ("certificate");
382
383                         foreach (X509Certificate2 x in certificates)
384                                 Remove (x);
385                 }
386
387                 [MonoTODO ("Method isn't transactional (like documented)")]
388                 public void RemoveRange (X509Certificate2Collection certificates) 
389                 {
390                         if (certificates == null)
391                                 throw new ArgumentNullException ("certificate");
392
393                         foreach (X509Certificate2 x in certificates)
394                                 Remove (x);
395                 }
396         }
397 }
398
399 #endif