2 // X509Store.cs: Handles a X.509 certificates/CRLs store
5 // Sebastien Pouliot <sebastien@ximian.com>
6 // Pablo Ruiz <pruiz@netway.org>
8 // Copyright (C) 2004 Novell, Inc (http://www.novell.com)
9 // (C) 2010 Pablo Ruiz.
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Globalization;
36 using System.Security.Cryptography;
38 using Mono.Security.Cryptography;
39 using Mono.Security.X509.Extensions;
41 namespace Mono.Security.X509 {
50 private string _storePath;
51 private X509CertificateCollection _certificates;
52 private ArrayList _crls;
56 internal X509Store (string path, bool crl)
64 public X509CertificateCollection Certificates {
66 if (_certificates == null) {
67 _certificates = BuildCertificatesCollection (_storePath);
73 public ArrayList Crls {
75 // CRL aren't applicable to all stores
76 // but returning null is a little rude
78 _crls = new ArrayList ();
81 _crls = BuildCrlsCollection (_storePath);
90 int n = _storePath.LastIndexOf (Path.DirectorySeparatorChar);
91 _name = _storePath.Substring (n+1);
102 * Both _certificates and _crls extend CollectionBase, whose Clear() method calls OnClear() and
103 * OnClearComplete(), which should be overridden in derivative classes. So we should not worry about
104 * other threads that might be holding references to _certificates or _crls. They should be smart enough
105 * to handle this gracefully. And if not, it's their own fault.
107 ClearCertificates ();
111 void ClearCertificates()
113 if (_certificates != null)
114 _certificates.Clear ();
115 _certificates = null;
125 public void Import (X509Certificate certificate)
127 CheckStore (_storePath, true);
129 string filename = Path.Combine (_storePath, GetUniqueName (certificate));
130 if (!File.Exists (filename)) {
131 using (FileStream fs = File.Create (filename)) {
132 byte[] data = certificate.RawData;
133 fs.Write (data, 0, data.Length);
136 ClearCertificates (); // We have modified the store on disk. So forget the old state.
139 // Try to save privateKey if available..
140 CspParameters cspParams = new CspParameters ();
141 cspParams.KeyContainerName = CryptoConvert.ToHex (certificate.Hash);
143 // Right now this seems to be the best way to know if we should use LM store.. ;)
144 if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
145 cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
147 ImportPrivateKey (certificate, cspParams);
151 public void Import (X509Crl crl)
153 CheckStore (_storePath, true);
155 string filename = Path.Combine (_storePath, GetUniqueName (crl));
156 if (!File.Exists (filename)) {
157 using (FileStream fs = File.Create (filename)) {
158 byte[] data = crl.RawData;
159 fs.Write (data, 0, data.Length);
161 ClearCrls (); // We have modified the store on disk. So forget the old state.
165 public void Remove (X509Certificate certificate)
167 string filename = Path.Combine (_storePath, GetUniqueName (certificate));
168 if (File.Exists (filename)) {
169 File.Delete (filename);
170 ClearCertificates (); // We have modified the store on disk. So forget the old state.
174 public void Remove (X509Crl crl)
176 string filename = Path.Combine (_storePath, GetUniqueName (crl));
177 if (File.Exists (filename)) {
178 File.Delete (filename);
179 ClearCrls (); // We have modified the store on disk. So forget the old state.
185 private string GetUniqueName (X509Certificate certificate)
188 byte[] name = GetUniqueName (certificate.Extensions);
190 method = "tbp"; // thumbprint
191 name = certificate.Hash;
195 return GetUniqueName (method, name, ".cer");
198 private string GetUniqueName (X509Crl crl)
201 byte[] name = GetUniqueName (crl.Extensions);
203 method = "tbp"; // thumbprint
208 return GetUniqueName (method, name, ".crl");
211 private byte[] GetUniqueName (X509ExtensionCollection extensions)
213 // We prefer Subject Key Identifier as the unique name
214 // as it will provide faster lookups
215 X509Extension ext = extensions ["2.5.29.14"];
219 SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension (ext);
220 return ski.Identifier;
223 private string GetUniqueName (string method, byte[] name, string fileExtension)
225 StringBuilder sb = new StringBuilder (method);
228 foreach (byte b in name) {
229 sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
231 sb.Append (fileExtension);
233 return sb.ToString ();
236 private byte[] Load (string filename)
239 using (FileStream fs = File.OpenRead (filename)) {
240 data = new byte [fs.Length];
241 fs.Read (data, 0, data.Length);
247 private X509Certificate LoadCertificate (string filename)
249 byte[] data = Load (filename);
250 X509Certificate cert = new X509Certificate (data);
252 // If privateKey it's available, load it too..
253 CspParameters cspParams = new CspParameters ();
254 cspParams.KeyContainerName = CryptoConvert.ToHex (cert.Hash);
255 if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
256 cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
257 KeyPairPersistence kpp = new KeyPairPersistence (cspParams);
267 if (cert.RSA != null)
268 cert.RSA = new RSACryptoServiceProvider (cspParams);
269 else if (cert.DSA != null)
270 cert.DSA = new DSACryptoServiceProvider (cspParams);
275 private X509Crl LoadCrl (string filename)
277 byte[] data = Load (filename);
278 X509Crl crl = new X509Crl (data);
282 private bool CheckStore (string path, bool throwException)
285 if (Directory.Exists (path))
287 Directory.CreateDirectory (path);
288 return Directory.Exists (path);
297 private X509CertificateCollection BuildCertificatesCollection (string storeName)
299 X509CertificateCollection coll = new X509CertificateCollection ();
300 string path = Path.Combine (_storePath, storeName);
301 if (!CheckStore (path, false))
302 return coll; // empty collection
304 string[] files = Directory.GetFiles (path, "*.cer");
305 if ((files != null) && (files.Length > 0)) {
306 foreach (string file in files) {
308 X509Certificate cert = LoadCertificate (file);
312 // in case someone is dumb enough
313 // (like me) to include a base64
314 // encoded certs (or other junk
322 private ArrayList BuildCrlsCollection (string storeName)
324 ArrayList list = new ArrayList ();
325 string path = Path.Combine (_storePath, storeName);
326 if (!CheckStore (path, false))
327 return list; // empty list
329 string[] files = Directory.GetFiles (path, "*.crl");
330 if ((files != null) && (files.Length > 0)) {
331 foreach (string file in files) {
333 X509Crl crl = LoadCrl (file);
344 private void ImportPrivateKey (X509Certificate certificate, CspParameters cspParams)
346 RSACryptoServiceProvider rsaCsp = certificate.RSA as RSACryptoServiceProvider;
347 if (rsaCsp != null) {
348 if (rsaCsp.PublicOnly)
351 RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
352 csp.ImportParameters(rsaCsp.ExportParameters(true));
353 csp.PersistKeyInCsp = true;
357 RSAManaged rsaMng = certificate.RSA as RSAManaged;
358 if (rsaMng != null) {
359 if (rsaMng.PublicOnly)
362 RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
363 csp.ImportParameters(rsaMng.ExportParameters(true));
364 csp.PersistKeyInCsp = true;
368 DSACryptoServiceProvider dsaCsp = certificate.DSA as DSACryptoServiceProvider;
369 if (dsaCsp != null) {
370 if (dsaCsp.PublicOnly)
373 DSACryptoServiceProvider csp = new DSACryptoServiceProvider(cspParams);
374 csp.ImportParameters(dsaCsp.ExportParameters(true));
375 csp.PersistKeyInCsp = true;