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);
101 if (_certificates != null)
102 _certificates.Clear ();
103 _certificates = null;
109 public void Import (X509Certificate certificate)
111 CheckStore (_storePath, true);
113 string filename = Path.Combine (_storePath, GetUniqueName (certificate));
114 if (!File.Exists (filename)) {
115 using (FileStream fs = File.Create (filename)) {
116 byte[] data = certificate.RawData;
117 fs.Write (data, 0, data.Length);
122 // Try to save privateKey if available..
123 CspParameters cspParams = new CspParameters ();
124 cspParams.KeyContainerName = CryptoConvert.ToHex (certificate.Hash);
126 // Right now this seems to be the best way to know if we should use LM store.. ;)
127 if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
128 cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
130 ImportPrivateKey (certificate, cspParams);
134 public void Import (X509Crl crl)
136 CheckStore (_storePath, true);
138 string filename = Path.Combine (_storePath, GetUniqueName (crl));
139 if (!File.Exists (filename)) {
140 using (FileStream fs = File.Create (filename)) {
141 byte[] data = crl.RawData;
142 fs.Write (data, 0, data.Length);
147 public void Remove (X509Certificate certificate)
149 string filename = Path.Combine (_storePath, GetUniqueName (certificate));
150 if (File.Exists (filename)) {
151 File.Delete (filename);
155 public void Remove (X509Crl crl)
157 string filename = Path.Combine (_storePath, GetUniqueName (crl));
158 if (File.Exists (filename)) {
159 File.Delete (filename);
165 private string GetUniqueName (X509Certificate certificate)
168 byte[] name = GetUniqueName (certificate.Extensions);
170 method = "tbp"; // thumbprint
171 name = certificate.Hash;
175 return GetUniqueName (method, name, ".cer");
178 private string GetUniqueName (X509Crl crl)
181 byte[] name = GetUniqueName (crl.Extensions);
183 method = "tbp"; // thumbprint
188 return GetUniqueName (method, name, ".crl");
191 private byte[] GetUniqueName (X509ExtensionCollection extensions)
193 // We prefer Subject Key Identifier as the unique name
194 // as it will provide faster lookups
195 X509Extension ext = extensions ["2.5.29.14"];
199 SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension (ext);
200 return ski.Identifier;
203 private string GetUniqueName (string method, byte[] name, string fileExtension)
205 StringBuilder sb = new StringBuilder (method);
208 foreach (byte b in name) {
209 sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
211 sb.Append (fileExtension);
213 return sb.ToString ();
216 private byte[] Load (string filename)
219 using (FileStream fs = File.OpenRead (filename)) {
220 data = new byte [fs.Length];
221 fs.Read (data, 0, data.Length);
227 private X509Certificate LoadCertificate (string filename)
229 byte[] data = Load (filename);
230 X509Certificate cert = new X509Certificate (data);
232 // If privateKey it's available, load it too..
233 CspParameters cspParams = new CspParameters ();
234 cspParams.KeyContainerName = CryptoConvert.ToHex (cert.Hash);
235 cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
236 KeyPairPersistence kpp = new KeyPairPersistence (cspParams);
241 if (cert.RSA != null)
242 cert.RSA = new RSACryptoServiceProvider (cspParams);
243 else if (cert.DSA != null)
244 cert.DSA = new DSACryptoServiceProvider (cspParams);
249 private X509Crl LoadCrl (string filename)
251 byte[] data = Load (filename);
252 X509Crl crl = new X509Crl (data);
256 private bool CheckStore (string path, bool throwException)
259 if (Directory.Exists (path))
261 Directory.CreateDirectory (path);
262 return Directory.Exists (path);
271 private X509CertificateCollection BuildCertificatesCollection (string storeName)
273 X509CertificateCollection coll = new X509CertificateCollection ();
274 string path = Path.Combine (_storePath, storeName);
275 if (!CheckStore (path, false))
276 return coll; // empty collection
278 string[] files = Directory.GetFiles (path, "*.cer");
279 if ((files != null) && (files.Length > 0)) {
280 foreach (string file in files) {
282 X509Certificate cert = LoadCertificate (file);
286 // in case someone is dumb enough
287 // (like me) to include a base64
288 // encoded certs (or other junk
296 private ArrayList BuildCrlsCollection (string storeName)
298 ArrayList list = new ArrayList ();
299 string path = Path.Combine (_storePath, storeName);
300 if (!CheckStore (path, false))
301 return list; // empty list
303 string[] files = Directory.GetFiles (path, "*.crl");
304 if ((files != null) && (files.Length > 0)) {
305 foreach (string file in files) {
307 X509Crl crl = LoadCrl (file);
318 private void ImportPrivateKey (X509Certificate certificate, CspParameters cspParams)
320 RSACryptoServiceProvider rsaCsp = certificate.RSA as RSACryptoServiceProvider;
321 if (rsaCsp != null) {
322 if (rsaCsp.PublicOnly)
325 RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
326 csp.ImportParameters(rsaCsp.ExportParameters(true));
327 csp.PersistKeyInCsp = true;
331 RSAManaged rsaMng = certificate.RSA as RSAManaged;
332 if (rsaMng != null) {
333 if (rsaMng.PublicOnly)
336 RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
337 csp.ImportParameters(rsaMng.ExportParameters(true));
338 csp.PersistKeyInCsp = true;
342 DSACryptoServiceProvider dsaCsp = certificate.DSA as DSACryptoServiceProvider;
343 if (dsaCsp != null) {
344 if (dsaCsp.PublicOnly)
347 DSACryptoServiceProvider csp = new DSACryptoServiceProvider(cspParams);
348 csp.ImportParameters(dsaCsp.ExportParameters(true));
349 csp.PersistKeyInCsp = true;