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 if (_storePath.StartsWith (X509StoreManager.LocalMachinePath))
236 cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
237 KeyPairPersistence kpp = new KeyPairPersistence (cspParams);
242 if (cert.RSA != null)
243 cert.RSA = new RSACryptoServiceProvider (cspParams);
244 else if (cert.DSA != null)
245 cert.DSA = new DSACryptoServiceProvider (cspParams);
250 private X509Crl LoadCrl (string filename)
252 byte[] data = Load (filename);
253 X509Crl crl = new X509Crl (data);
257 private bool CheckStore (string path, bool throwException)
260 if (Directory.Exists (path))
262 Directory.CreateDirectory (path);
263 return Directory.Exists (path);
272 private X509CertificateCollection BuildCertificatesCollection (string storeName)
274 X509CertificateCollection coll = new X509CertificateCollection ();
275 string path = Path.Combine (_storePath, storeName);
276 if (!CheckStore (path, false))
277 return coll; // empty collection
279 string[] files = Directory.GetFiles (path, "*.cer");
280 if ((files != null) && (files.Length > 0)) {
281 foreach (string file in files) {
283 X509Certificate cert = LoadCertificate (file);
287 // in case someone is dumb enough
288 // (like me) to include a base64
289 // encoded certs (or other junk
297 private ArrayList BuildCrlsCollection (string storeName)
299 ArrayList list = new ArrayList ();
300 string path = Path.Combine (_storePath, storeName);
301 if (!CheckStore (path, false))
302 return list; // empty list
304 string[] files = Directory.GetFiles (path, "*.crl");
305 if ((files != null) && (files.Length > 0)) {
306 foreach (string file in files) {
308 X509Crl crl = LoadCrl (file);
319 private void ImportPrivateKey (X509Certificate certificate, CspParameters cspParams)
321 RSACryptoServiceProvider rsaCsp = certificate.RSA as RSACryptoServiceProvider;
322 if (rsaCsp != null) {
323 if (rsaCsp.PublicOnly)
326 RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
327 csp.ImportParameters(rsaCsp.ExportParameters(true));
328 csp.PersistKeyInCsp = true;
332 RSAManaged rsaMng = certificate.RSA as RSAManaged;
333 if (rsaMng != null) {
334 if (rsaMng.PublicOnly)
337 RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
338 csp.ImportParameters(rsaMng.ExportParameters(true));
339 csp.PersistKeyInCsp = true;
343 DSACryptoServiceProvider dsaCsp = certificate.DSA as DSACryptoServiceProvider;
344 if (dsaCsp != null) {
345 if (dsaCsp.PublicOnly)
348 DSACryptoServiceProvider csp = new DSACryptoServiceProvider(cspParams);
349 csp.ImportParameters(dsaCsp.ExportParameters(true));
350 csp.PersistKeyInCsp = true;