98cc608119ca00b6a07699a49e627a5809ca374f
[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.Runtime.InteropServices;
34 #if !NET_2_1
35 using System.Security.Permissions;
36 #endif
37 using MX = Mono.Security.X509;
38
39 namespace System.Security.Cryptography.X509Certificates
40 {
41         static partial class X509Helper
42         {
43 #if !NET_2_1
44                 // typedef struct _CERT_CONTEXT {
45                 //      DWORD                   dwCertEncodingType;
46                 //      BYTE                    *pbCertEncoded;
47                 //      DWORD                   cbCertEncoded;
48                 //      PCERT_INFO              pCertInfo;
49                 //      HCERTSTORE              hCertStore;
50                 // } CERT_CONTEXT, *PCERT_CONTEXT;
51                 // typedef const CERT_CONTEXT *PCCERT_CONTEXT;
52                 [StructLayout (LayoutKind.Sequential)]
53                 internal struct CertificateContext {
54                         public UInt32 dwCertEncodingType;
55                         public IntPtr pbCertEncoded;
56                         public UInt32 cbCertEncoded;
57                         public IntPtr pCertInfo;
58                         public IntPtr hCertStore;
59                 }
60                 // NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
61                 // so we don't create any dependencies on Windows DLL in corlib
62
63                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
64                 public static X509CertificateImpl InitFromHandle (IntPtr handle)
65                 {
66                         // both Marshal.PtrToStructure and Marshal.Copy use LinkDemand (so they will always success from here)
67                         CertificateContext cc = (CertificateContext) Marshal.PtrToStructure (handle, typeof (CertificateContext));
68                         byte[] data = new byte [cc.cbCertEncoded];
69                         Marshal.Copy (cc.pbCertEncoded, data, 0, (int)cc.cbCertEncoded);
70                         var x509 = new MX.X509Certificate (data);
71                         return new X509CertificateImplMono (x509);
72                 }
73 #else
74                 public static X509CertificateImpl InitFromHandle (IntPtr handle)
75                 {
76                         throw new NotSupportedException ();
77                 }
78 #endif
79
80                 public static X509CertificateImpl InitFromCertificate (X509CertificateImpl impl)
81                 {
82                         ThrowIfContextInvalid (impl);
83                         var copy = impl.Clone ();
84                         if (copy != null)
85                                 return copy;
86
87                         var data = impl.GetRawCertData ();
88                         if (data == null)
89                                 return null;
90
91                         var x509 = new MX.X509Certificate (data);
92                         return new X509CertificateImplMono (x509);
93                 }
94
95                 public static bool IsValid (X509CertificateImpl impl)
96                 {
97                         return impl != null && impl.IsValid;
98                 }
99
100                 internal static void ThrowIfContextInvalid (X509CertificateImpl impl)
101                 {
102                         if (!IsValid (impl))
103                                 throw GetInvalidContextException ();
104                 }
105
106                 internal static Exception GetInvalidContextException ()
107                 {
108                         return new CryptographicException (Locale.GetText ("Certificate instance is empty."));
109                 }
110
111                 internal static MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
112                 {
113                         var pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
114                         if (pfx.Certificates.Count == 0) {
115                                 // no certificate was found
116                                 return null;
117                         } else if (pfx.Keys.Count == 0) {
118                                 // no key were found - pick the first certificate
119                                 return pfx.Certificates [0];
120                         } else {
121                                 // find the certificate that match the first key
122                                 var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
123                                 string pubkey = keypair.ToXmlString (false);
124                                 foreach (var c in pfx.Certificates) {
125                                         if ((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false)))
126                                                 return c;
127                                         if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
128                                                 return c;
129                                 }
130                                 return pfx.Certificates [0]; // no match, pick first certificate without keys
131                         }
132                 }
133
134 #if !MONOTOUCH && !XAMMAC
135                 public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
136                 {
137                         MX.X509Certificate x509;
138                         if (password == null) {
139                                 try {
140                                         x509 = new MX.X509Certificate (rawData);
141                                 } catch (Exception e) {
142                                         try {
143                                                 x509 = ImportPkcs12 (rawData, null);
144                                         } catch {
145                                                 string msg = Locale.GetText ("Unable to decode certificate.");
146                                                 // inner exception is the original (not second) exception
147                                                 throw new CryptographicException (msg, e);
148                                         }
149                                 }
150                         } else {
151                                 // try PKCS#12
152                                 try {
153                                         x509 = ImportPkcs12 (rawData, password);
154                                 }
155                                 catch {
156                                         // it's possible to supply a (unrequired/unusued) password
157                                         // fix bug #79028
158                                         x509 = new MX.X509Certificate (rawData);
159                                 }
160                         }
161
162                         return new X509CertificateImplMono (x509);
163                 }
164 #else
165                 public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
166                 {
167                         throw new NotSupportedException ();
168                 }               
169 #endif
170
171                 public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password)
172                 {
173                         ThrowIfContextInvalid (impl);
174                         return impl.Export (contentType, password);
175                 }
176
177                 public static bool Equals (X509CertificateImpl first, X509CertificateImpl second)
178                 {
179                         if (!IsValid (first) || !IsValid (second))
180                                 return false;
181
182                         bool result;
183                         if (first.Equals (second, out result))
184                                 return result;
185
186                         var firstRaw = first.GetRawCertData ();
187                         var secondRaw = second.GetRawCertData ();
188
189                         if (firstRaw == null)
190                                 return secondRaw == null;
191                         else if (secondRaw == null)
192                                 return false;
193
194                         if (firstRaw.Length != secondRaw.Length)
195                                 return false;
196
197                         for (int i = 0; i < firstRaw.Length; i++) {
198                                 if (firstRaw [i] != secondRaw [i])
199                                         return false;
200                         }
201
202                         return true;
203                 }
204
205                 // almost every byte[] returning function has a string equivalent
206                 // sadly the BitConverter insert dash between bytes :-(
207                 public static string ToHexString (byte[] data)
208                 {
209                         if (data != null) {
210                                 StringBuilder sb = new StringBuilder ();
211                                 for (int i = 0; i < data.Length; i++)
212                                         sb.Append (data[i].ToString ("X2"));
213                                 return sb.ToString ();
214                         }
215                         else
216                                 return null;
217                 }
218         }
219 }