[mcs] Replace NET_2_1 by MOBILE
[mono.git] / mcs / class / corlib / System.Security.Cryptography.X509Certificates / X509Helper.cs
1 //
2 // X509Helpers.cs: X.509 helper and utility functions.
3 //
4 // Authors:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //      Martin Baulig  <martin.baulig@xamarin.com>
7 //
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)
11 //
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:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
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.
30 //
31 using System;
32 using System.Text;
33 using System.Threading;
34 using System.Runtime.InteropServices;
35 #if !MOBILE
36 using System.Security.Permissions;
37 #endif
38 using MX = Mono.Security.X509;
39
40 namespace System.Security.Cryptography.X509Certificates
41 {
42         static partial class X509Helper
43         {
44                 static INativeCertificateHelper nativeHelper;
45
46                 internal static void InstallNativeHelper (INativeCertificateHelper helper)
47                 {
48                         if (nativeHelper == null)
49                                 Interlocked.CompareExchange (ref nativeHelper, helper, null);
50                 }
51
52 #if !MOBILE
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;
68                 }
69                 // NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
70                 // so we don't create any dependencies on Windows DLL in corlib
71
72                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
73                 public static X509CertificateImpl InitFromHandle (IntPtr handle)
74                 {
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);
81                 }
82 #elif !MONOTOUCH && !XAMMAC
83                 public static X509CertificateImpl InitFromHandle (IntPtr handle)
84                 {
85                         throw new NotSupportedException ();
86                 }
87 #endif
88
89                 public static X509CertificateImpl InitFromCertificate (X509Certificate cert)
90                 {
91                         if (nativeHelper != null)
92                                 return nativeHelper.Import (cert);
93
94                         return InitFromCertificate (cert.Impl);
95                 }
96
97                 public static X509CertificateImpl InitFromCertificate (X509CertificateImpl impl)
98                 {
99                         ThrowIfContextInvalid (impl);
100                         var copy = impl.Clone ();
101                         if (copy != null)
102                                 return copy;
103
104                         var data = impl.GetRawCertData ();
105                         if (data == null)
106                                 return null;
107
108                         var x509 = new MX.X509Certificate (data);
109                         return new X509CertificateImplMono (x509);
110                 }
111
112                 public static bool IsValid (X509CertificateImpl impl)
113                 {
114                         return impl != null && impl.IsValid;
115                 }
116
117                 internal static void ThrowIfContextInvalid (X509CertificateImpl impl)
118                 {
119                         if (!IsValid (impl))
120                                 throw GetInvalidContextException ();
121                 }
122
123                 internal static Exception GetInvalidContextException ()
124                 {
125                         return new CryptographicException (Locale.GetText ("Certificate instance is empty."));
126                 }
127
128                 internal static MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
129                 {
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
133                                 return null;
134                         } else if (pfx.Keys.Count == 0) {
135                                 // no key were found - pick the first certificate
136                                 return pfx.Certificates [0];
137                         } else {
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)))
143                                                 return c;
144                                         if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
145                                                 return c;
146                                 }
147                                 return pfx.Certificates [0]; // no match, pick first certificate without keys
148                         }
149                 }
150
151                 static byte[] PEM (string type, byte[] data)
152                 {
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);
160                 }
161
162                 static byte[] ConvertData (byte[] data)
163                 {
164                         if (data == null || data.Length == 0)
165                                 return data;
166
167                         // does it looks like PEM ?
168                         if (data [0] != 0x30) {
169                                 try {
170                                         return PEM ("CERTIFICATE", data);
171                                 } catch {
172                                         // let the implementation take care of it.
173                                 }
174                         }
175                         return data;
176                 }
177
178 #if !MONOTOUCH && !XAMMAC
179                 static X509CertificateImpl Import (byte[] rawData)
180                 {
181                         MX.X509Certificate x509;
182                         try {
183                                 x509 = new MX.X509Certificate (rawData);
184                         } catch (Exception e) {
185                                 try {
186                                         x509 = ImportPkcs12 (rawData, null);
187                                 } catch {
188                                         string msg = Locale.GetText ("Unable to decode certificate.");
189                                         // inner exception is the original (not second) exception
190                                         throw new CryptographicException (msg, e);
191                                 }
192                         }
193
194                         return new X509CertificateImplMono (x509);
195                 }
196 #endif
197
198                 public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
199                 {
200                         if (password == null) {
201                                 rawData = ConvertData (rawData);
202                                 return Import (rawData);
203                         }
204
205                         MX.X509Certificate x509;
206                         // try PKCS#12
207                         try {
208                                 x509 = ImportPkcs12 (rawData, password);
209                         } catch {
210                                 // it's possible to supply a (unrequired/unusued) password
211                                 // fix bug #79028
212                                 x509 = new MX.X509Certificate (rawData);
213                         }
214
215                         return new X509CertificateImplMono (x509);
216                 }
217
218                 public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password)
219                 {
220                         ThrowIfContextInvalid (impl);
221                         return impl.Export (contentType, password);
222                 }
223
224                 public static bool Equals (X509CertificateImpl first, X509CertificateImpl second)
225                 {
226                         if (!IsValid (first) || !IsValid (second))
227                                 return false;
228
229                         bool result;
230                         if (first.Equals (second, out result))
231                                 return result;
232
233                         var firstRaw = first.GetRawCertData ();
234                         var secondRaw = second.GetRawCertData ();
235
236                         if (firstRaw == null)
237                                 return secondRaw == null;
238                         else if (secondRaw == null)
239                                 return false;
240
241                         if (firstRaw.Length != secondRaw.Length)
242                                 return false;
243
244                         for (int i = 0; i < firstRaw.Length; i++) {
245                                 if (firstRaw [i] != secondRaw [i])
246                                         return false;
247                         }
248
249                         return true;
250                 }
251
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)
255                 {
256                         if (data != null) {
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 ();
261                         }
262                         else
263                                 return null;
264                 }
265         }
266 }