Imported Upstream version 4.3.2.467

Former-commit-id: 9c2cb47f45fa221e661ab616387c9cda183f283d
This commit is contained in:
Xamarin Public Jenkins
2016-02-22 11:00:01 -05:00
parent f302175246
commit f3e3aab35a
4097 changed files with 122406 additions and 82300 deletions

View File

@@ -53,42 +53,9 @@ namespace System.Security.Cryptography.X509Certificates {
#else
public partial class X509Certificate : IDeserializationCallback, ISerializable {
#endif
// typedef struct _CERT_CONTEXT {
// DWORD dwCertEncodingType;
// BYTE *pbCertEncoded;
// DWORD cbCertEncoded;
// PCERT_INFO pCertInfo;
// HCERTSTORE hCertStore;
// } CERT_CONTEXT, *PCERT_CONTEXT;
// typedef const CERT_CONTEXT *PCCERT_CONTEXT;
[StructLayout (LayoutKind.Sequential)]
internal struct CertificateContext {
public UInt32 dwCertEncodingType;
public IntPtr pbCertEncoded;
public UInt32 cbCertEncoded;
public IntPtr pCertInfo;
public IntPtr hCertStore;
}
// NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
// so we don't create any dependencies on Windows DLL in corlib
X509CertificateImpl impl;
private Mono.Security.X509.X509Certificate x509;
private bool hideDates;
private byte[] cachedCertificateHash;
// almost every byte[] returning function has a string equivalent
// sadly the BitConverter insert dash between bytes :-(
private string tostr (byte[] data)
{
if (data != null) {
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < data.Length; i++)
sb.Append (data[i].ToString ("X2"));
return sb.ToString ();
}
else
return null;
}
// static methods
@@ -133,44 +100,24 @@ namespace System.Security.Cryptography.X509Certificates {
public X509Certificate (byte[] data) : this (data, true)
{
}
public X509Certificate (IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentException ("Invalid handle.");
#if NET_2_1
// this works on Windows-only so it's of no use for Moonlight
// even more since this ctor is [SecurityCritical]
throw new NotSupportedException ();
#else
InitFromHandle (handle);
#endif
impl = X509Helper.InitFromHandle (handle);
}
[SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
private void InitFromHandle (IntPtr handle)
{
if (handle != IntPtr.Zero) {
// both Marshal.PtrToStructure and Marshal.Copy use LinkDemand (so they will always success from here)
CertificateContext cc = (CertificateContext) Marshal.PtrToStructure (handle, typeof (CertificateContext));
byte[] data = new byte [cc.cbCertEncoded];
Marshal.Copy (cc.pbCertEncoded, data, 0, (int)cc.cbCertEncoded);
x509 = new Mono.Security.X509.X509Certificate (data);
}
// for 1.x IntPtr.Zero results in an "empty" certificate instance
}
public X509Certificate (System.Security.Cryptography.X509Certificates.X509Certificate cert)
{
if (cert == null)
throw new ArgumentNullException ("cert");
if (cert != null) {
byte[] data = cert.GetRawCertData ();
if (data != null)
x509 = new Mono.Security.X509.X509Certificate (data);
hideDates = false;
}
X509Helper.ThrowIfContextInvalid (cert.impl);
impl = X509Helper.InitFromCertificate (cert.impl);
hideDates = false;
}
@@ -181,53 +128,30 @@ namespace System.Security.Cryptography.X509Certificates {
if (other == null) {
return false;
} else {
if (other.x509 == null) {
if (x509 == null)
if (!X509Helper.IsValid (other.impl)) {
if (!X509Helper.IsValid (impl))
return true;
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
}
byte[] raw = other.x509.RawData;
if (raw != null) {
if (x509 == null)
return false;
if (x509.RawData == null)
return false;
if (raw.Length == x509.RawData.Length) {
for (int i = 0; i < raw.Length; i++) {
if (raw[i] != x509.RawData [i])
return false;
}
// well no choice must be equals!
return true;
}
else
return false;
}
return X509CertificateImpl.Equals (impl, other.impl);
}
return ((x509 == null) || (x509.RawData == null));
}
// LAMESPEC: This is the equivalent of the "thumbprint" that can be seen
// in the certificate viewer of Windows. This is ALWAYS the SHA1 hash of
// the certificate (i.e. it has nothing to do with the actual hash
// algorithm used to sign the certificate).
public virtual byte[] GetCertHash ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
// we'll hash the cert only once and only if required
if ((cachedCertificateHash == null) && (x509 != null)) {
SHA1 sha = SHA1.Create ();
cachedCertificateHash = sha.ComputeHash (x509.RawData);
}
return cachedCertificateHash;
X509Helper.ThrowIfContextInvalid (impl);
return impl.GetCertHash ();
}
public virtual string GetCertHashString ()
{
// must call GetCertHash (not variable) or optimization wont work
return tostr (GetCertHash ());
return X509Helper.ToHexString (GetCertHash ());
}
// strangly there are no DateTime returning function
@@ -235,10 +159,9 @@ namespace System.Security.Cryptography.X509Certificates {
{
if (hideDates)
return null;
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
X509Helper.ThrowIfContextInvalid (impl);
return x509.ValidFrom.ToLocalTime ().ToString ();
return impl.GetEffectiveDateString ().ToString ();
}
// strangly there are no DateTime returning function
@@ -246,10 +169,9 @@ namespace System.Security.Cryptography.X509Certificates {
{
if (hideDates)
return null;
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
X509Helper.ThrowIfContextInvalid (impl);
return x509.ValidUntil.ToLocalTime ().ToString ();
return impl.GetExpirationDateString ().ToString ();
}
// well maybe someday there'll be support for PGP or SPKI ?
@@ -260,41 +182,29 @@ namespace System.Security.Cryptography.X509Certificates {
public override int GetHashCode ()
{
if (x509 == null)
return 0;
// the cert hash may not be (yet) calculated
if (cachedCertificateHash == null)
GetCertHash();
// return the integer of the first 4 bytes of the cert hash
if ((cachedCertificateHash != null) && (cachedCertificateHash.Length >= 4))
return ((cachedCertificateHash[0] << 24) |(cachedCertificateHash[1] << 16) |
(cachedCertificateHash[2] << 8) | cachedCertificateHash[3]);
else
if (!X509Helper.IsValid (impl))
return 0;
return impl.GetHashCode ();
}
[Obsolete ("Use the Issuer property.")]
public virtual string GetIssuerName ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
return x509.IssuerName;
X509Helper.ThrowIfContextInvalid (impl);
return impl.GetIssuerName (true);
}
public virtual string GetKeyAlgorithm ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
return x509.KeyAlgorithm;
X509Helper.ThrowIfContextInvalid (impl);
return impl.GetKeyAlgorithm ();
}
public virtual byte[] GetKeyAlgorithmParameters ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
X509Helper.ThrowIfContextInvalid (impl);
byte[] kap = x509.KeyAlgorithmParameters;
byte[] kap = impl.GetKeyAlgorithmParameters ();
if (kap == null)
throw new CryptographicException (Locale.GetText ("Parameters not part of the certificate"));
@@ -303,55 +213,50 @@ namespace System.Security.Cryptography.X509Certificates {
public virtual string GetKeyAlgorithmParametersString ()
{
return tostr (GetKeyAlgorithmParameters ());
return X509Helper.ToHexString (GetKeyAlgorithmParameters ());
}
[Obsolete ("Use the Subject property.")]
public virtual string GetName ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
return x509.SubjectName;
X509Helper.ThrowIfContextInvalid (impl);
return impl.GetSubjectName (true);
}
public virtual byte[] GetPublicKey ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
return x509.PublicKey;
X509Helper.ThrowIfContextInvalid (impl);
return impl.GetPublicKey ();
}
public virtual string GetPublicKeyString ()
{
return tostr (GetPublicKey ());
return X509Helper.ToHexString (GetPublicKey ());
}
public virtual byte[] GetRawCertData ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
return x509.RawData;
X509Helper.ThrowIfContextInvalid (impl);
return impl.GetRawCertData ();
}
public virtual string GetRawCertDataString ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
return tostr (x509.RawData);
X509Helper.ThrowIfContextInvalid (impl);
return X509Helper.ToHexString (impl.GetRawCertData ());
}
public virtual byte[] GetSerialNumber ()
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
return x509.SerialNumber;
X509Helper.ThrowIfContextInvalid (impl);
return impl.GetSerialNumber ();
}
public virtual string GetSerialNumberString ()
{
byte[] sn = GetSerialNumber ();
Array.Reverse (sn);
return tostr (sn);
return X509Helper.ToHexString (sn);
}
// to please corcompare ;-)
@@ -362,18 +267,10 @@ namespace System.Security.Cryptography.X509Certificates {
public virtual string ToString (bool fVerbose)
{
if (!fVerbose || (x509 == null))
if (!fVerbose || !X509Helper.IsValid (impl))
return base.ToString ();
string nl = Environment.NewLine;
StringBuilder sb = new StringBuilder ();
sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, Subject);
sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, Issuer);
sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, GetEffectiveDateString ());
sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, GetExpirationDateString ());
sb.AppendFormat ("[Thumbprint]{0} {1}{0}", nl, GetCertHashString ());
sb.Append (nl);
return sb.ToString ();
return impl.ToString (true);
}
protected static string FormatDate (DateTime date)

View File

@@ -42,7 +42,7 @@ namespace System.Security.Cryptography.X509Certificates {
[ComVisible (true)]
[MonoTODO ("X509ContentType.SerializedCert isn't supported (anywhere in the class)")]
public partial class X509Certificate : IDeserializationCallback, ISerializable {
public partial class X509Certificate : IDeserializationCallback, ISerializable, IDisposable {
private string issuer_name;
private string subject_name;
@@ -110,29 +110,31 @@ namespace System.Security.Cryptography.X509Certificates {
public string Issuer {
get {
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
X509Helper.ThrowIfContextInvalid (impl);
if (issuer_name == null)
issuer_name = X501.ToString (x509.GetIssuerName (), true, ", ", true);
issuer_name = impl.GetIssuerName (false);
return issuer_name;
}
}
public string Subject {
get {
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
X509Helper.ThrowIfContextInvalid (impl);
if (subject_name == null)
subject_name = X501.ToString (x509.GetSubjectName (), true, ", ", true);
subject_name = impl.GetSubjectName (false);
return subject_name;
}
}
[ComVisible (false)]
public IntPtr Handle {
get { return IntPtr.Zero; }
get {
if (X509Helper.IsValid (impl))
return impl.Handle;
return IntPtr.Zero;
}
}
@@ -169,25 +171,10 @@ namespace System.Security.Cryptography.X509Certificates {
internal byte[] Export (X509ContentType contentType, byte[] password)
{
if (x509 == null)
throw new CryptographicException (Locale.GetText ("Certificate instance is empty."));
try {
switch (contentType) {
case X509ContentType.Cert:
return x509.RawData;
case X509ContentType.Pfx: // this includes Pkcs12
// TODO
throw new NotSupportedException ();
case X509ContentType.SerializedCert:
// TODO
throw new NotSupportedException ();
default:
string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
throw new CryptographicException (msg);
}
}
finally {
X509Helper.ThrowIfContextInvalid (impl);
return impl.Export (contentType, password);
} finally {
// protect password
if (password != null)
Array.Clear (password, 0, password.Length);
@@ -200,59 +187,12 @@ namespace System.Security.Cryptography.X509Certificates {
Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
}
private Mono.Security.X509.X509Certificate ImportPkcs12 (byte[] rawData, string password)
{
var pfx = (password == null) ? new Mono.Security.X509.PKCS12 (rawData) : new Mono.Security.X509.PKCS12 (rawData, password);
if (pfx.Certificates.Count == 0) {
// no certificate was found
return null;
} else if (pfx.Keys.Count == 0) {
// no key were found - pick the first certificate
return pfx.Certificates [0];
} else {
// find the certificate that match the first key
var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
string pubkey = keypair.ToXmlString (false);
foreach (var c in pfx.Certificates) {
if ((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false)))
return c;
if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
return c;
}
return pfx.Certificates [0]; // no match, pick first certificate without keys
}
}
[MonoTODO ("missing KeyStorageFlags support")]
[ComVisible (false)]
public virtual void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
Reset ();
if (password == null) {
try {
x509 = new Mono.Security.X509.X509Certificate (rawData);
}
catch (Exception e) {
try {
x509 = ImportPkcs12 (rawData, null);
}
catch {
string msg = Locale.GetText ("Unable to decode certificate.");
// inner exception is the original (not second) exception
throw new CryptographicException (msg, e);
}
}
} else {
// try PKCS#12
try {
x509 = ImportPkcs12 (rawData, password);
}
catch {
// it's possible to supply a (unrequired/unusued) password
// fix bug #79028
x509 = new Mono.Security.X509.X509Certificate (rawData);
}
}
impl = X509Helper.Import (rawData, password, keyStorageFlags);
}
[MonoTODO ("SecureString support is incomplete")]
@@ -289,18 +229,34 @@ namespace System.Security.Cryptography.X509Certificates {
void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
{
if (!X509Helper.IsValid (impl))
throw new NullReferenceException ();
// will throw a NRE if info is null (just like MS implementation)
info.AddValue ("RawData", x509.RawData);
info.AddValue ("RawData", impl.GetRawCertData ());
}
public void Dispose ()
{
Dispose (true);
}
protected virtual void Dispose (bool disposing)
{
if (disposing)
Reset ();
}
[ComVisible (false)]
public virtual void Reset ()
{
x509 = null;
if (impl != null) {
impl.Dispose ();
impl = null;
}
issuer_name = null;
subject_name = null;
hideDates = false;
cachedCertificateHash = null;
}
}
}

View File

@@ -0,0 +1,148 @@
//
// X509Helpers.cs: X.509 helper and utility functions.
//
// Authors:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (C) 2015 Xamarin, Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.Security.Cryptography.X509Certificates
{
internal abstract class X509CertificateImpl : IDisposable
{
public abstract bool IsValid {
get;
}
public abstract IntPtr Handle {
get;
}
protected void ThrowIfContextInvalid ()
{
if (!IsValid)
throw X509Helper.GetInvalidContextException ();
}
public abstract X509CertificateImpl Clone ();
public abstract string GetSubjectSummary ();
public abstract string GetIssuerName (bool legacyV1Mode);
public abstract string GetSubjectName (bool legacyV1Mode);
public abstract byte[] GetRawCertData ();
public abstract DateTime GetEffectiveDateString ();
public abstract DateTime GetExpirationDateString ();
byte[] cachedCertificateHash;
public byte[] GetCertHash ()
{
ThrowIfContextInvalid ();
if (cachedCertificateHash == null)
cachedCertificateHash = GetCertHash (false);
return cachedCertificateHash;
}
protected abstract byte[] GetCertHash (bool lazy);
public override int GetHashCode ()
{
if (!IsValid)
return 0;
if (cachedCertificateHash == null)
cachedCertificateHash = GetCertHash (true);
// return the integer of the first 4 bytes of the cert hash
if ((cachedCertificateHash != null) && (cachedCertificateHash.Length >= 4))
return ((cachedCertificateHash [0] << 24) | (cachedCertificateHash [1] << 16) |
(cachedCertificateHash [2] << 8) | cachedCertificateHash [3]);
else
return 0;
}
public abstract bool Equals (X509CertificateImpl other, out bool result);
public abstract string GetKeyAlgorithm ();
public abstract byte[] GetKeyAlgorithmParameters ();
public abstract byte[] GetPublicKey ();
public abstract byte[] GetSerialNumber ();
public abstract byte[] Export (X509ContentType contentType, byte[] password);
public abstract string ToString (bool full);
public override bool Equals (object obj)
{
var other = obj as X509CertificateImpl;
if (other == null)
return false;
if (!IsValid || !other.IsValid)
return false;
bool result;
if (Equals (other, out result))
return result;
var ourRaw = GetRawCertData ();
var theirRaw = other.GetRawCertData ();
if (ourRaw == null)
return theirRaw == null;
else if (theirRaw == null)
return false;
if (ourRaw.Length != theirRaw.Length)
return false;
for (int i = 0; i < ourRaw.Length; i++) {
if (ourRaw [i] != theirRaw [i])
return false;
}
return true;
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
cachedCertificateHash = null;
}
~X509CertificateImpl ()
{
Dispose (false);
}
}
}

View File

@@ -0,0 +1,179 @@
//
// X509CertificateImplMono.cs: X.509 implementation using Mono.Security.X509.
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
// Martin Baulig <martin.baulig@xamarin.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
// Copyright (C) 2015 Xamarin, Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using MX = Mono.Security.X509;
namespace System.Security.Cryptography.X509Certificates
{
class X509CertificateImplMono : X509CertificateImpl
{
MX.X509Certificate x509;
public X509CertificateImplMono (MX.X509Certificate x509)
{
this.x509 = x509;
}
public override bool IsValid {
get { return x509 != null; }
}
public override IntPtr Handle {
get { return IntPtr.Zero; }
}
public override X509CertificateImpl Clone ()
{
ThrowIfContextInvalid ();
return new X509CertificateImplMono (x509);
}
public override string GetIssuerName (bool legacyV1Mode)
{
ThrowIfContextInvalid ();
if (legacyV1Mode)
return x509.IssuerName;
else
return MX.X501.ToString (x509.GetIssuerName (), true, ", ", true);
}
public override string GetSubjectSummary ()
{
ThrowIfContextInvalid ();
return x509.SubjectName;
}
public override string GetSubjectName (bool legacyV1Mode)
{
ThrowIfContextInvalid ();
if (legacyV1Mode)
return x509.SubjectName;
else
return MX.X501.ToString (x509.GetSubjectName (), true, ", ", true);
}
public override byte[] GetRawCertData ()
{
ThrowIfContextInvalid ();
return x509.RawData;
}
protected override byte[] GetCertHash (bool lazy)
{
ThrowIfContextInvalid ();
SHA1 sha = SHA1.Create ();
return sha.ComputeHash (x509.RawData);
}
public override DateTime GetEffectiveDateString ()
{
ThrowIfContextInvalid ();
return x509.ValidFrom.ToLocalTime ();
}
public override DateTime GetExpirationDateString ()
{
ThrowIfContextInvalid ();
return x509.ValidUntil.ToLocalTime ();
}
public override bool Equals (X509CertificateImpl other, out bool result)
{
// Use default implementation
result = false;
return false;
}
public override string GetKeyAlgorithm ()
{
ThrowIfContextInvalid ();
return x509.KeyAlgorithm;
}
public override byte[] GetKeyAlgorithmParameters ()
{
ThrowIfContextInvalid ();
return x509.KeyAlgorithmParameters;
}
public override byte[] GetPublicKey ()
{
ThrowIfContextInvalid ();
return x509.PublicKey;
}
public override byte[] GetSerialNumber ()
{
ThrowIfContextInvalid ();
return x509.SerialNumber;
}
public override byte[] Export (X509ContentType contentType, byte[] password)
{
ThrowIfContextInvalid ();
switch (contentType) {
case X509ContentType.Cert:
return GetRawCertData ();
case X509ContentType.Pfx: // this includes Pkcs12
// TODO
throw new NotSupportedException ();
case X509ContentType.SerializedCert:
// TODO
throw new NotSupportedException ();
default:
string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
throw new CryptographicException (msg);
}
}
public override string ToString (bool full)
{
ThrowIfContextInvalid ();
string nl = Environment.NewLine;
StringBuilder sb = new StringBuilder ();
sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, GetSubjectName (false));
sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, GetIssuerName (false));
sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, GetEffectiveDateString ());
sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, GetExpirationDateString ());
sb.AppendFormat ("[Thumbprint]{0} {1}{0}", nl, X509Helper.ToHexString (GetCertHash ()));
sb.Append (nl);
return sb.ToString ();
}
protected override void Dispose (bool disposing)
{
x509 = null;
}
}
}

View File

@@ -0,0 +1,214 @@
//
// X509Helpers.cs: X.509 helper and utility functions.
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
// Martin Baulig <martin.baulig@xamarin.com>
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
// Copyright (C) 2015 Xamarin, Inc. (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Runtime.InteropServices;
#if !NET_2_1
using System.Security.Permissions;
#endif
using MX = Mono.Security.X509;
namespace System.Security.Cryptography.X509Certificates
{
static partial class X509Helper
{
#if !NET_2_1
// typedef struct _CERT_CONTEXT {
// DWORD dwCertEncodingType;
// BYTE *pbCertEncoded;
// DWORD cbCertEncoded;
// PCERT_INFO pCertInfo;
// HCERTSTORE hCertStore;
// } CERT_CONTEXT, *PCERT_CONTEXT;
// typedef const CERT_CONTEXT *PCCERT_CONTEXT;
[StructLayout (LayoutKind.Sequential)]
internal struct CertificateContext {
public UInt32 dwCertEncodingType;
public IntPtr pbCertEncoded;
public UInt32 cbCertEncoded;
public IntPtr pCertInfo;
public IntPtr hCertStore;
}
// NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
// so we don't create any dependencies on Windows DLL in corlib
[SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
public static X509CertificateImpl InitFromHandle (IntPtr handle)
{
// both Marshal.PtrToStructure and Marshal.Copy use LinkDemand (so they will always success from here)
CertificateContext cc = (CertificateContext) Marshal.PtrToStructure (handle, typeof (CertificateContext));
byte[] data = new byte [cc.cbCertEncoded];
Marshal.Copy (cc.pbCertEncoded, data, 0, (int)cc.cbCertEncoded);
var x509 = new MX.X509Certificate (data);
return new X509CertificateImplMono (x509);
}
#elif !MONOTOUCH && !XAMMAC
public static X509CertificateImpl InitFromHandle (IntPtr handle)
{
throw new NotSupportedException ();
}
#endif
public static X509CertificateImpl InitFromCertificate (X509CertificateImpl impl)
{
ThrowIfContextInvalid (impl);
var copy = impl.Clone ();
if (copy != null)
return copy;
var data = impl.GetRawCertData ();
if (data == null)
return null;
var x509 = new MX.X509Certificate (data);
return new X509CertificateImplMono (x509);
}
public static bool IsValid (X509CertificateImpl impl)
{
return impl != null && impl.IsValid;
}
internal static void ThrowIfContextInvalid (X509CertificateImpl impl)
{
if (!IsValid (impl))
throw GetInvalidContextException ();
}
internal static Exception GetInvalidContextException ()
{
return new CryptographicException (Locale.GetText ("Certificate instance is empty."));
}
internal static MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
{
var pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
if (pfx.Certificates.Count == 0) {
// no certificate was found
return null;
} else if (pfx.Keys.Count == 0) {
// no key were found - pick the first certificate
return pfx.Certificates [0];
} else {
// find the certificate that match the first key
var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
string pubkey = keypair.ToXmlString (false);
foreach (var c in pfx.Certificates) {
if ((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false)))
return c;
if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
return c;
}
return pfx.Certificates [0]; // no match, pick first certificate without keys
}
}
#if !MONOTOUCH && !XAMMAC
public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
MX.X509Certificate x509;
if (password == null) {
try {
x509 = new MX.X509Certificate (rawData);
} catch (Exception e) {
try {
x509 = ImportPkcs12 (rawData, null);
} catch {
string msg = Locale.GetText ("Unable to decode certificate.");
// inner exception is the original (not second) exception
throw new CryptographicException (msg, e);
}
}
} else {
// try PKCS#12
try {
x509 = ImportPkcs12 (rawData, password);
}
catch {
// it's possible to supply a (unrequired/unusued) password
// fix bug #79028
x509 = new MX.X509Certificate (rawData);
}
}
return new X509CertificateImplMono (x509);
}
#endif
public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password)
{
ThrowIfContextInvalid (impl);
return impl.Export (contentType, password);
}
public static bool Equals (X509CertificateImpl first, X509CertificateImpl second)
{
if (!IsValid (first) || !IsValid (second))
return false;
bool result;
if (first.Equals (second, out result))
return result;
var firstRaw = first.GetRawCertData ();
var secondRaw = second.GetRawCertData ();
if (firstRaw == null)
return secondRaw == null;
else if (secondRaw == null)
return false;
if (firstRaw.Length != secondRaw.Length)
return false;
for (int i = 0; i < firstRaw.Length; i++) {
if (firstRaw [i] != secondRaw [i])
return false;
}
return true;
}
// almost every byte[] returning function has a string equivalent
// sadly the BitConverter insert dash between bytes :-(
public static string ToHexString (byte[] data)
{
if (data != null) {
StringBuilder sb = new StringBuilder ();
for (int i = 0; i < data.Length; i++)
sb.Append (data[i].ToString ("X2"));
return sb.ToString ();
}
else
return null;
}
}
}