2 // X509Helpers.cs: X.509 helper and utility functions.
5 // Sebastien Pouliot <sebastien@ximian.com>
6 // Martin Baulig <martin.baulig@xamarin.com>
8 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
10 // Copyright (C) 2015 Xamarin, Inc. (http://www.xamarin.com)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
33 using System.Threading;
34 using System.Runtime.InteropServices;
36 using System.Security.Permissions;
38 using MX = Mono.Security.X509;
40 namespace System.Security.Cryptography.X509Certificates
42 static partial class X509Helper
44 static INativeCertificateHelper nativeHelper;
46 internal static void InstallNativeHelper (INativeCertificateHelper helper)
48 if (nativeHelper == null)
49 Interlocked.CompareExchange (ref nativeHelper, helper, null);
52 #if MONO_FEATURE_APPLETLS
53 static bool ShouldUseAppleTls
57 if (!System.Environment.IsMacOS)
59 // MONO_TLS_PROVIDER values default or apple (not legacy or btls) and must be on MacOS
60 var variable = Environment.GetEnvironmentVariable ("MONO_TLS_PROVIDER");
61 return string.IsNullOrEmpty (variable) || variable == "default" || variable == "apple"; // On Platform.IsMacOS default is AppleTlsProvider
66 public static X509CertificateImpl InitFromHandle (IntPtr handle)
68 #if MONO_FEATURE_APPLETLS && ONLY_APPLETLS // ONLY_APPLETLS should not support any other option
69 return InitFromHandleApple (handle);
71 throw new PlatformNotSupportedException ();
74 #if MONO_FEATURE_APPLETLS // If we support AppleTls, which is the default, and not overriding to legacy
75 if (ShouldUseAppleTls)
76 return InitFromHandleApple (handle);
79 return InitFromHandleCore (handle);
80 #elif !MONOTOUCH && !XAMMAC
81 throw new NotSupportedException ();
86 static X509CertificateImpl Import (byte[] rawData)
88 #if MONO_FEATURE_APPLETLS && ONLY_APPLETLS // ONLY_APPLETLS should not support any other option
89 return ImportApple (rawData);
91 throw new PlatformNotSupportedException ();
93 #if MONO_FEATURE_APPLETLS
94 if (ShouldUseAppleTls)
95 return ImportApple (rawData);
97 return ImportCore (rawData);
102 // typedef struct _CERT_CONTEXT {
103 // DWORD dwCertEncodingType;
104 // BYTE *pbCertEncoded;
105 // DWORD cbCertEncoded;
106 // PCERT_INFO pCertInfo;
107 // HCERTSTORE hCertStore;
108 // } CERT_CONTEXT, *PCERT_CONTEXT;
109 // typedef const CERT_CONTEXT *PCCERT_CONTEXT;
110 [StructLayout (LayoutKind.Sequential)]
111 internal struct CertificateContext {
112 public UInt32 dwCertEncodingType;
113 public IntPtr pbCertEncoded;
114 public UInt32 cbCertEncoded;
115 public IntPtr pCertInfo;
116 public IntPtr hCertStore;
118 // NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
119 // so we don't create any dependencies on Windows DLL in corlib
121 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
122 public static X509CertificateImpl InitFromHandleCore (IntPtr handle)
124 // both Marshal.PtrToStructure and Marshal.Copy use LinkDemand (so they will always success from here)
125 CertificateContext cc = (CertificateContext) Marshal.PtrToStructure (handle, typeof (CertificateContext));
126 byte[] data = new byte [cc.cbCertEncoded];
127 Marshal.Copy (cc.pbCertEncoded, data, 0, (int)cc.cbCertEncoded);
128 var x509 = new MX.X509Certificate (data);
129 return new X509CertificateImplMono (x509);
133 public static X509CertificateImpl InitFromCertificate (X509Certificate cert)
135 if (nativeHelper != null)
136 return nativeHelper.Import (cert);
138 return InitFromCertificate (cert.Impl);
141 public static X509CertificateImpl InitFromCertificate (X509CertificateImpl impl)
143 ThrowIfContextInvalid (impl);
144 var copy = impl.Clone ();
148 var data = impl.GetRawCertData ();
152 var x509 = new MX.X509Certificate (data);
153 return new X509CertificateImplMono (x509);
156 public static bool IsValid (X509CertificateImpl impl)
158 return impl != null && impl.IsValid;
161 internal static void ThrowIfContextInvalid (X509CertificateImpl impl)
164 throw GetInvalidContextException ();
167 internal static Exception GetInvalidContextException ()
169 return new CryptographicException (Locale.GetText ("Certificate instance is empty."));
172 internal static MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
174 var pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
175 if (pfx.Certificates.Count == 0) {
176 // no certificate was found
178 } else if (pfx.Keys.Count == 0) {
179 // no key were found - pick the first certificate
180 return pfx.Certificates [0];
182 // find the certificate that match the first key
183 var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
184 string pubkey = keypair.ToXmlString (false);
185 foreach (var c in pfx.Certificates) {
186 if ((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false)))
188 if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
191 return pfx.Certificates [0]; // no match, pick first certificate without keys
195 static byte[] PEM (string type, byte[] data)
197 string pem = Encoding.ASCII.GetString (data);
198 string header = String.Format ("-----BEGIN {0}-----", type);
199 string footer = String.Format ("-----END {0}-----", type);
200 int start = pem.IndexOf (header) + header.Length;
201 int end = pem.IndexOf (footer, start);
202 string base64 = pem.Substring (start, (end - start));
203 return Convert.FromBase64String (base64);
206 static byte[] ConvertData (byte[] data)
208 if (data == null || data.Length == 0)
211 // does it looks like PEM ?
212 if (data [0] != 0x30) {
214 return PEM ("CERTIFICATE", data);
216 // let the implementation take care of it.
222 static X509CertificateImpl ImportCore (byte[] rawData)
224 MX.X509Certificate x509;
226 x509 = new MX.X509Certificate (rawData);
227 } catch (Exception e) {
229 x509 = ImportPkcs12 (rawData, null);
231 string msg = Locale.GetText ("Unable to decode certificate.");
232 // inner exception is the original (not second) exception
233 throw new CryptographicException (msg, e);
237 return new X509CertificateImplMono (x509);
240 public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
242 if (password == null) {
243 rawData = ConvertData (rawData);
244 return Import (rawData);
247 MX.X509Certificate x509;
250 x509 = ImportPkcs12 (rawData, password);
252 // it's possible to supply a (unrequired/unusued) password
254 x509 = new MX.X509Certificate (rawData);
257 return new X509CertificateImplMono (x509);
260 public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password)
262 ThrowIfContextInvalid (impl);
263 return impl.Export (contentType, password);
266 public static bool Equals (X509CertificateImpl first, X509CertificateImpl second)
268 if (!IsValid (first) || !IsValid (second))
272 if (first.Equals (second, out result))
275 var firstRaw = first.GetRawCertData ();
276 var secondRaw = second.GetRawCertData ();
278 if (firstRaw == null)
279 return secondRaw == null;
280 else if (secondRaw == null)
283 if (firstRaw.Length != secondRaw.Length)
286 for (int i = 0; i < firstRaw.Length; i++) {
287 if (firstRaw [i] != secondRaw [i])
294 // almost every byte[] returning function has a string equivalent
295 // sadly the BitConverter insert dash between bytes :-(
296 public static string ToHexString (byte[] data)
299 StringBuilder sb = new StringBuilder ();
300 for (int i = 0; i < data.Length; i++)
301 sb.Append (data[i].ToString ("X2"));
302 return sb.ToString ();