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.Runtime.InteropServices;
35 using System.Security.Permissions;
37 using MX = Mono.Security.X509;
39 namespace System.Security.Cryptography.X509Certificates
41 static partial class X509Helper
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;
60 // NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
61 // so we don't create any dependencies on Windows DLL in corlib
63 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
64 public static X509CertificateImpl InitFromHandle (IntPtr handle)
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);
73 #elif !MONOTOUCH && !XAMMAC
74 public static X509CertificateImpl InitFromHandle (IntPtr handle)
76 throw new NotSupportedException ();
80 public static X509CertificateImpl InitFromCertificate (X509CertificateImpl impl)
82 ThrowIfContextInvalid (impl);
83 var copy = impl.Clone ();
87 var data = impl.GetRawCertData ();
91 var x509 = new MX.X509Certificate (data);
92 return new X509CertificateImplMono (x509);
95 public static bool IsValid (X509CertificateImpl impl)
97 return impl != null && impl.IsValid;
100 internal static void ThrowIfContextInvalid (X509CertificateImpl impl)
103 throw GetInvalidContextException ();
106 internal static Exception GetInvalidContextException ()
108 return new CryptographicException (Locale.GetText ("Certificate instance is empty."));
111 internal static MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
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
117 } else if (pfx.Keys.Count == 0) {
118 // no key were found - pick the first certificate
119 return pfx.Certificates [0];
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)))
127 if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
130 return pfx.Certificates [0]; // no match, pick first certificate without keys
134 #if !MONOTOUCH && !XAMMAC
135 public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
137 MX.X509Certificate x509;
138 if (password == null) {
140 x509 = new MX.X509Certificate (rawData);
141 } catch (Exception e) {
143 x509 = ImportPkcs12 (rawData, null);
145 string msg = Locale.GetText ("Unable to decode certificate.");
146 // inner exception is the original (not second) exception
147 throw new CryptographicException (msg, e);
153 x509 = ImportPkcs12 (rawData, password);
156 // it's possible to supply a (unrequired/unusued) password
158 x509 = new MX.X509Certificate (rawData);
162 return new X509CertificateImplMono (x509);
166 public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password)
168 ThrowIfContextInvalid (impl);
169 return impl.Export (contentType, password);
172 public static bool Equals (X509CertificateImpl first, X509CertificateImpl second)
174 if (!IsValid (first) || !IsValid (second))
178 if (first.Equals (second, out result))
181 var firstRaw = first.GetRawCertData ();
182 var secondRaw = second.GetRawCertData ();
184 if (firstRaw == null)
185 return secondRaw == null;
186 else if (secondRaw == null)
189 if (firstRaw.Length != secondRaw.Length)
192 for (int i = 0; i < firstRaw.Length; i++) {
193 if (firstRaw [i] != secondRaw [i])
200 // almost every byte[] returning function has a string equivalent
201 // sadly the BitConverter insert dash between bytes :-(
202 public static string ToHexString (byte[] data)
205 StringBuilder sb = new StringBuilder ();
206 for (int i = 0; i < data.Length; i++)
207 sb.Append (data[i].ToString ("X2"));
208 return sb.ToString ();