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);
53 // typedef struct _CERT_CONTEXT {
54 // DWORD dwCertEncodingType;
55 // BYTE *pbCertEncoded;
56 // DWORD cbCertEncoded;
57 // PCERT_INFO pCertInfo;
58 // HCERTSTORE hCertStore;
59 // } CERT_CONTEXT, *PCERT_CONTEXT;
60 // typedef const CERT_CONTEXT *PCCERT_CONTEXT;
61 [StructLayout (LayoutKind.Sequential)]
62 internal struct CertificateContext {
63 public UInt32 dwCertEncodingType;
64 public IntPtr pbCertEncoded;
65 public UInt32 cbCertEncoded;
66 public IntPtr pCertInfo;
67 public IntPtr hCertStore;
69 // NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
70 // so we don't create any dependencies on Windows DLL in corlib
72 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
73 public static X509CertificateImpl InitFromHandle (IntPtr handle)
75 // both Marshal.PtrToStructure and Marshal.Copy use LinkDemand (so they will always success from here)
76 CertificateContext cc = (CertificateContext) Marshal.PtrToStructure (handle, typeof (CertificateContext));
77 byte[] data = new byte [cc.cbCertEncoded];
78 Marshal.Copy (cc.pbCertEncoded, data, 0, (int)cc.cbCertEncoded);
79 var x509 = new MX.X509Certificate (data);
80 return new X509CertificateImplMono (x509);
82 #elif !MONOTOUCH && !XAMMAC
83 public static X509CertificateImpl InitFromHandle (IntPtr handle)
85 throw new NotSupportedException ();
89 public static X509CertificateImpl InitFromCertificate (X509Certificate cert)
91 if (nativeHelper != null)
92 return nativeHelper.Import (cert);
94 return InitFromCertificate (cert.Impl);
97 public static X509CertificateImpl InitFromCertificate (X509CertificateImpl impl)
99 ThrowIfContextInvalid (impl);
100 var copy = impl.Clone ();
104 var data = impl.GetRawCertData ();
108 var x509 = new MX.X509Certificate (data);
109 return new X509CertificateImplMono (x509);
112 public static bool IsValid (X509CertificateImpl impl)
114 return impl != null && impl.IsValid;
117 internal static void ThrowIfContextInvalid (X509CertificateImpl impl)
120 throw GetInvalidContextException ();
123 internal static Exception GetInvalidContextException ()
125 return new CryptographicException (Locale.GetText ("Certificate instance is empty."));
128 internal static MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
130 var pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
131 if (pfx.Certificates.Count == 0) {
132 // no certificate was found
134 } else if (pfx.Keys.Count == 0) {
135 // no key were found - pick the first certificate
136 return pfx.Certificates [0];
138 // find the certificate that match the first key
139 var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
140 string pubkey = keypair.ToXmlString (false);
141 foreach (var c in pfx.Certificates) {
142 if ((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false)))
144 if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
147 return pfx.Certificates [0]; // no match, pick first certificate without keys
151 static byte[] PEM (string type, byte[] data)
153 string pem = Encoding.ASCII.GetString (data);
154 string header = String.Format ("-----BEGIN {0}-----", type);
155 string footer = String.Format ("-----END {0}-----", type);
156 int start = pem.IndexOf (header) + header.Length;
157 int end = pem.IndexOf (footer, start);
158 string base64 = pem.Substring (start, (end - start));
159 return Convert.FromBase64String (base64);
162 static byte[] ConvertData (byte[] data)
164 if (data == null || data.Length == 0)
167 // does it looks like PEM ?
168 if (data [0] != 0x30) {
170 return PEM ("CERTIFICATE", data);
172 // let the implementation take care of it.
178 #if !MONOTOUCH && !XAMMAC
179 static X509CertificateImpl Import (byte[] rawData)
181 MX.X509Certificate x509;
183 x509 = new MX.X509Certificate (rawData);
184 } catch (Exception e) {
186 x509 = ImportPkcs12 (rawData, null);
188 string msg = Locale.GetText ("Unable to decode certificate.");
189 // inner exception is the original (not second) exception
190 throw new CryptographicException (msg, e);
194 return new X509CertificateImplMono (x509);
198 public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
200 if (password == null) {
201 rawData = ConvertData (rawData);
202 return Import (rawData);
205 MX.X509Certificate x509;
208 x509 = ImportPkcs12 (rawData, password);
210 // it's possible to supply a (unrequired/unusued) password
212 x509 = new MX.X509Certificate (rawData);
215 return new X509CertificateImplMono (x509);
218 public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password)
220 ThrowIfContextInvalid (impl);
221 return impl.Export (contentType, password);
224 public static bool Equals (X509CertificateImpl first, X509CertificateImpl second)
226 if (!IsValid (first) || !IsValid (second))
230 if (first.Equals (second, out result))
233 var firstRaw = first.GetRawCertData ();
234 var secondRaw = second.GetRawCertData ();
236 if (firstRaw == null)
237 return secondRaw == null;
238 else if (secondRaw == null)
241 if (firstRaw.Length != secondRaw.Length)
244 for (int i = 0; i < firstRaw.Length; i++) {
245 if (firstRaw [i] != secondRaw [i])
252 // almost every byte[] returning function has a string equivalent
253 // sadly the BitConverter insert dash between bytes :-(
254 public static string ToHexString (byte[] data)
257 StringBuilder sb = new StringBuilder ();
258 for (int i = 0; i < data.Length; i++)
259 sb.Append (data[i].ToString ("X2"));
260 return sb.ToString ();