Imported Upstream version 3.6.0

Former-commit-id: da6be194a6b1221998fc28233f2503bd61dd9d14
This commit is contained in:
Jo Shields
2014-08-13 10:39:27 +01:00
commit a575963da9
50588 changed files with 8155799 additions and 0 deletions

View File

@@ -0,0 +1,422 @@
2010-06-11 Jonathan Chambers <joncham@gmail.com>
* X509Certificate2Collection.cs: Add {} around default switch case.
2010-05-10 Sebastien Pouliot <sebastien@ximian.com>
* PublicKey.cs
* X500DistinguishedName.cs:
* X509BasicConstraintsExtension.cs:
* X509Certificate2Collection.cs:
* X509Certificate2.cs:
* X509Certificate2Enumerator.cs:
* X509Chain.cs:
* X509ChainElementCollection.cs:
* X509ChainElement.cs:
* X509ChainElementEnumerator.cs:
* X509ChainPolicy.cs:
* X509ChainStatus.cs:
* X509EnhancedKeyUsageExtension.cs:
* X509ExtensionCollection.cs:
* X509Extension.cs:
* X509ExtensionEnumerator.cs:
* X509KeyUsageExtension.cs:
* X509KeyUsageFlags.cs:
* X509NameType.cs:
* X509Store.cs:
* X509SubjectKeyIdentifierExtension.cs:
Allow parts required to enable SSL to be built with
the moonlight profile.
* X509_2_1_bootstrap.cs: New. Ease bootstrapping 2.1
2010-04-06 Geoff Norton <gnorton@novell.com>
* OSX509Certificates.cs: Fix a crash when doing multiple certificate calls
Fix a rare but possible leak.
2010-03-16 Jb Evain <jbevain@novell.com>
* X509Chain.cs: use MOONLIGHT symbol to disambiguate MonoTouch
and Moonlight code.
2010-03-11 Gonzalo Paniagua Javier <gonzalo@novell.com>
* OSX509Certificates.cs: moved here from Mono.Security.
2009-07-10 Gonzalo Paniagua Javier <gonzalo@novell.com>
* X509Chain.cs: revert my last change here since it caused 2 tests to
fail.
2009-07-02 Gonzalo Paniagua Javier <gonzalo@novell.com>
* X509Certificate2.cs:
* X509Chain.cs: changes to make everything compile with latest changes
and fixed typo in IsChainComplete().
2008-06-26 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2.cs: Allow password-less ctor to (try to) open
PKCS#12 files (with an empty password).
[Fix bug #403610]
2008-06-03 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2.cs: Allow PrivateKey property to be set to null.
[Fix bug #396620]
2008-05-18 Sebastien Pouliot <sebastien@ximian.com>
* X509Chain.cs: Use String.IsNullOrEmpty inside 2.0 code.
[Found using Gendarme]
2008-04-09 Gert Driesen <drieseng@users.sourceforge.net>
* X500DistinguishedName.cs: Fixed line endings.
* X509Chain.cs: Fixed line endings.
2008-01-13 Gert Driesen <drieseng@users.sourceforge.net>
* X509Certificate2.cs: NotAfter and NotBefore must return local time.
2007-05-09 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2.cs: Leave a small stub (PrivateKey property) if
SECURITY_DEP isn't defined. This will let Mono.Security.dll build
correctly under 2.0 while enabling the use of X509Certificate2 to add
support for X.509 client certificates in SSL/TLS.
2006-12-07 Sebastien Pouliot <sebastien@ximian.com>
* X500DistinguishedName.cs: Add an internal method to compare
(canonized) DN so the class can be used in X509Chain.
* X509Certificate2.cs: Expose the internal certificate (from Mono.
Security.dll) as X509Certificate2 isn't complete enough to implement
chaining.
* X509Chain.cs: A (working) *subset( of RFC3280 path building and
validation.
* X509ChainElementCollection.cs: Add help method Contains and change
Add not to require a flag parameter.
* X509ChainElement.cs: Keeps flags compressed (as flags!) and add
a method to uncompress them when validation is complete.
* X509Store.cs: Expose the internal store (from Mono.Security.dll) as
internal. Map Trust and Root as the same store (for compatibility).
2006-11-24 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2.cs: Modified Verify to use CryptoConfig to create
the X509Chain used to verify the certificate. This makes it possible
to change the default chaining (certificate path creation and
validation) algorithm.
* X509Chain.cs: Started implementation based on the options and error
codes defined. Work in progress (incomplete and needs a lot more test
cases).
* X509ChainElementCollection.cs: Added internal methods to Add and
Clear the collection.
* X509ChainElement.cs: Implemented, MonoTODO removed.
* X509ChainPolicy.cs: Add missing checks on enum-based properties.
Renamed fields to match guidelines.
* X509ChainStatus.cs: Provide a default StatusInformation value based
on the Status.
2006-11-22 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2Collection.cs: Remove comment that proved to be
false (unit tests prove otherwise).
* X509Store.cs: Integrate the new 2.0 stores with the existing stores
that Mono used since 1.0.
2006-11-17 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2Collection.cs: Implement Export (to DER encoded
format), Find (for most X509FindType), Import (for single
certificates), RemoveRange (but it's not transactional).
* X509Certificate2.cs: Fix Reset method to reset every field.
* X509ExtensionCollection.cs: Implement missing CopyTo. Fix exception
handling to match new unit tests.
* X509ExtensionEnumerator.cs: Fix recursion.
* X509SubjectKeyIdentifierExtension.cs: Add support for ctors
accepting a PublicKey instance.
2006-11-13 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2.cs: Throw a CryptographicException for (most)
properties if the certificate is "empty". Implement GetNameInfo for
X509NameType.SimpleName, EmailName and DnsName. Add detection for
X509ContentType.Pkcs7 in GetCertContentType.
2006-11-08 Sebastien Pouliot <sebastien@ximian.com>
* X500DistinguishedName.cs: Fix most common cases. Some flags are
still not supported.
* X509Certificate2.cs: Fix importing PKCS#12 certificates (with keys)
in some cases. Implement GetCertContentType for Cert, Pfx and Pkcs12.
Implement ToString methods.
* X509ExtensionCollection.cs: Add an internal ctor that can populate
the collection from extensions coming from an Mono.Security.X509.
X509Certificate. CryptoConfig is used to allow extensibility to the
X509Extension class.
2006-10-08 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2.cs: Ensure we can load certificates from read-only
files (fix bug #79616).
2006-10-05 Andrew Skiba <andrews@mainsoft.com>
* X509CertificateCollection.cs: remove IEnumerable private imple-
mentation to match MSDN.
2006-09-20 Atsushi Enomoto <atsushi@ximian.com>
* X509Certificate2.cs : in .ctor(X509Certificate) call base copy .ctor()
as well. Fixed bug #79455.
2006-09-12 Sebastien Pouliot <sebastien@ximian.com>
* PublicKey.cs: Never return the private key in the Key property, even
if it was available when creating the public key.
2006-09-11 Atsushi Enomoto <atsushi@ximian.com>
* X509Certificate2.cs : implemented HasPrivateKey. Return null
when the corresponding RSA or DSA has no private key.
2006-09-05 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2.cs: Call import in ctor to be sure the private key
will be decoded. Last fix for #79269.
2006-08-02 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2.cs: A unrequired password can be supplied to the
2.0 ctors. Fix bug #79028.
2006-08-02 Atsushi Enomoto <atsushi@ximian.com>
* X509Certificate2.cs : .ctor(string, string) and .ctor(string,
SecureString) should call proper base constructor method for each.
Implemented IssuerName. Fixed bug #78986.
2006-03-11 Miguel de Icaza <miguel@novell.com>
* X509Chain.cs: Flagged member as internal to avoid unused warning.
* X500DistinguishedName.cs: Comment out unused names and move
temporary unused variables inside the comments that were removed
2005-11-24 Sebastien Pouliot <sebastien@ximian.com>
* X500DistinguishedName.cs: Added validation (still missing parsing).
* X509Certificate2Enumerator.cs: Add missing IEnumerator.* methods.
2005-11-22 Sebastien Pouliot <sebastien@ximian.com>
* PublicKey.cs: Completed implementation for both RSA and DSA public
keys.
2005-11-08 Sebastien Pouliot <sebastien@ximian.com>
* OpenFlags.cs: Removed extra [Serializable] (not in 2.0).
* StoreLocation.cs: Removed extra [Serializable] (not in 2.0).
* StoreName.cs: Removed extra [Serializable] (not in 2.0).
* X500DistinguishedNameFlags.cs: Removed extra [Serializable] (!2.0).
* X509ChainStatusFlags.cs: Removed extra [Serializable] (not in 2.0).
* X509FindType.cs: Removed extra [Serializable] (not in 2.0).
* X509IncludeOption.cs: Removed extra [Serializable] (not in 2.0).
* X509RevocationFlag.cs: Removed extra [Serializable] (not in 2.0).
* X509RevocationMode.cs: Removed extra [Serializable] (not in 2.0).
* X509SubjectKeyIdentifierHashAlgorithm.cs: Removed extra
[Serializable] (not in 2.0).
* X509VerificationFlags.cs: Removed extra [Serializable] (not in 2.0).
2005-09-27 Sebastien Pouliot <sebastien@ximian.com>
* X509Certificate2Collection.cs: Class is not sealed. Removed Select
methods (moved to a new class in System.Security.dll).
* X509Certificate2.cs: Removed Display methods (moved to a new class
in System.Security.dll).
* X509SelectionFlag.cs: Removed. This enum is still in System.Security
* X509NameType.cs: Added new DnsFromAlternativeName value.
2005-09-26 Sebastien Pouliot <sebastien@ximian.com>
* All classes, except X509CertificateCollection, moved from
System.Security.dll assembly as part of 2.0 RC changes.
2005-04-27 Sebastien Pouliot <sebastien@ximian.com>
* X509BasicConstraintsExtension.cs: Now throw ArgumentNullException in
CopyFrom (fixed in beta2).
* X509CertificateEx.cs: Throw a CryptographicException in the RawData
property if no certificate is loaded in the instance.
* X509EnhancedKeyUsageExtension.cs: Now throw ArgumentNullException in
CopyFrom (fixed in beta2).
* X509Extension.cs: Now throw ArgumentNullException in CopyFrom (fixed
in beta2).
* X509KeyUsageExtension.cs: Now throw ArgumentNullException in
CopyFrom (fixed in beta2).
* X509Store.cs: Re-added certificate creation to get the exception.
* X509SubjectKeyIdentifierExtension.cs: Throw ArgumentNullException in
CopyFrom (fixed in beta2). Fix SubjectKeyIdentifier to return an empty
string (not null) after (unsucessful) decoding.
2005-04-26 Sebastien Pouliot <sebastien@ximian.com>
* X509CertificateEx.cs: Used new features from Mono.Security.dll to
load certificates and private keys from PKCS#12.
2005-04-24 Sebastien Pouliot <sebastien@ximian.com>
* X509CertificateEx.cs: Added new constructors and Import methods that
accept SecureString for passwords. Added new property HasPrivateKey and
Verify method.
* X509CertificateExCollection.cs: Added new constructor that accept a
single X509Certificate2.
* X509EnhancedKeyUsageExtension.cs: Fixed compiler warnings.
* X509KeyUsageExtension.cs: Fixed new enum name for CrlSign.
* X509KeyUsageFlags.cs: Fixed values and removed [Serializable].
* X509NameType.cs: Fixed values and removed [Serializable].
* X509Store.cs: Added new constructor that accept an IntPtr and the
StoreHandle property. Fixed compiler warnings.
2005-04-23 Sebastien Pouliot <sebastien@ximian.com>
* X509CertificateEx.cs, X509CertificateExCollection.cs,
X509CertificateExEnumerator.cs, X509Chain.cs, X509ChainElement.cs,
X509ChainPolicy.cs, X509Store.cs: Changed all references of
X509CertificateEx to X509Certificate2 to match beta2.
2005-01-17 Sebastien Pouliot <sebastien@ximian.com>
* X509BasicConstraintsExtension.cs: Completed implementation.
* X509Chain.cs: Updated to Dec CTP definitions.
* X509ChainPolicy.cs: Updated to Dec CTP definitions.
* X500DistinguishedNameFlags.cs: Added new ForceUTF8Encoding.
* X509EnhancedKeyUsageExtension.cs: New. Complete implementation.
* X509Extension.cs: Completed implementation.
* X509ExtensionCollection.cs: Updated to Dec CTP definitions.
* X509KeyUsageExtension.cs: Completed implementation.
* X509RevocationFlag.cs: Minus 1 on each member.
* X509SubjectKeyIdentifierExtension.cs: Completed implementation
except for the new constructor accepting a public key.
* X509SubjectKeyIdentifierHashAlgorithm.cs: New enum.
2004-09-03 Tim Coleman <tim@timcoleman.com>
* X509KeyUsageExtension.cs: New stub class
* X509SubjectKeyIdentifierExtension.cs: New stub class
* PublicKey.cs X509BasicConstraintsExtension.cs X509CertificateEx.cs
* X509CertificateExCollection.cs X509Extension.cs
* X509ExtensionCollection.cs:
Bring these more in line with 2.0
2004-07-08 Sebastien Pouliot <sebastien@ximian.com>
* OpenFlags.cs: Fixed flags values. Added missing attributes.
* StoreLocation.cs: Fixed enum values. Added missing [Serializable].
* StoreName.cs: Fixed enum values. Added missing [Serializable].
* X500DistinguishedName.cs: New. X.501 DN.
* X500DistinguishedNameFlags.cs: New. X.501 DN flags.
* X509CertificateEx.cs: Updated to Fx 2.0 beta 1. Added MonoTODO.
* X509Chain.cs: Added missing Reset method.
* X509ChainStatusFlags.cs: Fixed flags values. Added missing attrs.
* X509Extension.cs: Fixed API.
* X509ExtensionCollection.cs: Fixed API and implemented.
* X509FindType.cs: Fixed enum values. Added missing [Serializable].
* X509IncludeOption.cs: Added missing [Serializable].
* X509KeyUsageFlags.cs: : Fixed flags values. Added missing attrs.
* X509NameType.cs: Fixed enum values. Added missing [Serializable].
* X509RevocationFlag.cs: Fixed enum values. Added missing [Serializable].
* X509RevocationMode.cs: Added missing [Serializable].
* X509SelectionFlag.cs: Added missing [Serializable].
* X509VerificationFlags.cs: Fixed flags values. Added missing attrs.
2004-07-07 Sebastien Pouliot <sebastien@ximian.com>
* X509Store.cs: Removed old store code (as it has changed a lot in
Mono.Security).
2004-06-05 Sebastien Pouliot <sebastien@ximian.com>
* X509CertificateCollection.cs: Fixed Contains which works by value
(i.e. not by object reference). Fixed Remove for null and unexisting
elements.
2003-12-07 Sebastien Pouliot <spouliot@videotron.ca>
* PublicKey.cs: New (1.2). Class that encapsulate an ASN.1 encoded
public key.
* X509BasicConstraintsExtension.cs: New (1.2). X.509 certification
extension for BasicConstraints.
* X509CertificateEx.cs: New (1.2). Augmented class to use X.509
certificates.
* X509CertificateExCollection.cs: New (1.2). Collection class for
X509CertificateEx.
* X509CertificateExEnumerator.cs: New (1.2). Enumerator class for
X509CertificateEx.
* X509ChainElement.cs: New (1.2). Information (certificate, status,
informations) for a member of a certificate chain.
* X509ChainElementCollection.cs: New (1.2). Collection class for
X509ChainElement.
* X509ChainElementEnumerator.cs: New (1.2). Enumerator class for
X509ChainElement.
* X509ChainStatus.cs: New (1.2). Chain status (many can apply to a
single X509ChainElement).
* X509Extension.cs: New (1.2). Base class for all certificate
extensions.
* X509ExtensionCollection.cs: New (1.2). Collection class for
X509Extension.
* X509ExtensionEnumerator.cs: New (1.2). Enumerator class for
X509Extension.
2003-11-08 Sebastien Pouliot <spouliot@videotron.ca>
* OpenFlags.cs: New (1.2). Enumeration for certificate stores.
* StoreLocation.cs: New (1.2). Enumeration for certificate stores.
* StoreName.cs: New (1.2). Enumeration for certificate stores.
* X509Chain.cs: New (1.2). Class to build a certificate chain up to a
trusted anchor.
* X509ChainElement.cs: New (1.2). Element from the chain (certificate,
status and information) - only stubbed for now.
* X509ChainElementCollection.cs: New (1.2). Collection class for
X509ChainElement.
* X509ChainElementEnumerator.cs: New (1.2). Enumerator class for
X509ChainElement.
* X509ChainPolicy.cs: New (1.2). Policy to build a certificate chain.
* X509ChainStatusFlags.cs: New (1.2). Enumeration for chain status.
* X509FindType.cs: New (1.2). Enumeration for how to find X.509
certificates in stores.
* X509IncludeOption.cs: New (1.2). Enumeration for options about which
certificate(s) to store within a (pkcs7) structure.
* X509KeyUsageFlags.cs: New (1.2). Enumeration for specifying valid
usage for a keypair.
* X509NameType.cs: New (1.2). Enumeration for different types of name
that can be present inside a certificate.
* X509RevocationFlag.cs: New (1.2). Enumeration for specifying which
certificates should be verified for revocation in a chain.
* X509RevocationMode.cs: New (1.2). Enumeration for specifying how the
revocation process should find it's informations.
* X509SelectionFlag.cs: New (1.2). Enumeration about how to select
certificates (ui-related).
* X509Store.cs: New (1.2). X.509 certificate store access - not complete.
* X509VerificationFlags.cs: New (1.2). Enumeration for parameters
affecting the verification of a certificate chain.
2003-03-01 Sebastien Pouliot <spouliot@videotron.ca>
* X509CertificateCollection.cs: Fixed bugs in AddRange
(added the collection not the certificates in the collection).
2003-01-30 Sebastien Pouliot <spouliot@videotron.ca>
* X509CertificateCollection.cs: Replaced the use of the private
ArrayList by the protected InnerList (from CollectionBase) so
Count property now works.
2002-10-21 Miguel de Icaza <miguel@ximian.com>
* X509CertificateCollection.cs (Add): New method.
2002-05-12 Lawrence Pit <loz@cable.a2000.nl>
* X509CertificateCollection.cs: implemented

View File

@@ -0,0 +1,158 @@
// Copyright (C) 2010 Novell, Inc (http://www.novell.com)
// Copyright 2012-2014 Xamarin Inc.
//
// 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.
//
#if SECURITY_DEP
#if MONOTOUCH || MONODROID
using MSX = Mono.Security.X509;
#else
extern alias MonoSecurity;
using MSX = MonoSecurity::Mono.Security.X509;
#endif
using System;
using System.Runtime.InteropServices;
namespace System.Security.Cryptography.X509Certificates {
static class OSX509Certificates {
public const string SecurityLibrary = "/System/Library/Frameworks/Security.framework/Security";
public const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";
[DllImport (SecurityLibrary)]
extern static IntPtr SecCertificateCreateWithData (IntPtr allocator, IntPtr nsdataRef);
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ int SecTrustCreateWithCertificates (IntPtr certOrCertArray, IntPtr policies, out IntPtr sectrustref);
[DllImport (SecurityLibrary)]
extern static IntPtr SecPolicyCreateSSL ([MarshalAs (UnmanagedType.I1)] bool server, IntPtr cfStringHostname);
[DllImport (SecurityLibrary)]
extern static /* OSStatus */ int SecTrustEvaluate (IntPtr secTrustRef, out SecTrustResult secTrustResultTime);
[DllImport (CoreFoundationLibrary, CharSet=CharSet.Unicode)]
extern static IntPtr CFStringCreateWithCharacters (IntPtr allocator, string str, /* CFIndex */ IntPtr count);
[DllImport (CoreFoundationLibrary)]
unsafe extern static IntPtr CFDataCreate (IntPtr allocator, byte *bytes, /* CFIndex */ IntPtr length);
[DllImport (CoreFoundationLibrary)]
extern static void CFRelease (IntPtr handle);
[DllImport (CoreFoundationLibrary)]
extern static IntPtr CFArrayCreate (IntPtr allocator, IntPtr values, /* CFIndex */ IntPtr numValues, IntPtr callbacks);
// uint32_t
public enum SecTrustResult {
Invalid,
Proceed,
Confirm,
Deny,
Unspecified,
RecoverableTrustFailure,
FatalTrustFailure,
ResultOtherError,
}
static IntPtr MakeCFData (byte [] data)
{
unsafe {
fixed (byte *ptr = &data [0])
return CFDataCreate (IntPtr.Zero, ptr, (IntPtr) data.Length);
}
}
static unsafe IntPtr FromIntPtrs (IntPtr [] values)
{
fixed (IntPtr* pv = values) {
return CFArrayCreate (
IntPtr.Zero,
(IntPtr) pv,
(IntPtr) values.Length,
IntPtr.Zero);
}
}
public static SecTrustResult TrustEvaluateSsl (MSX.X509CertificateCollection certificates, string host)
{
if (certificates == null)
return SecTrustResult.Deny;
try {
return _TrustEvaluateSsl (certificates, host);
} catch {
return SecTrustResult.Deny;
}
}
static SecTrustResult _TrustEvaluateSsl (MSX.X509CertificateCollection certificates, string hostName)
{
int certCount = certificates.Count;
IntPtr [] cfDataPtrs = new IntPtr [certCount];
IntPtr [] secCerts = new IntPtr [certCount];
IntPtr certArray = IntPtr.Zero;
IntPtr sslsecpolicy = IntPtr.Zero;
IntPtr host = IntPtr.Zero;
IntPtr sectrust = IntPtr.Zero;
SecTrustResult result = SecTrustResult.Deny;
try {
for (int i = 0; i < certCount; i++)
cfDataPtrs [i] = MakeCFData (certificates [i].RawData);
for (int i = 0; i < certCount; i++){
secCerts [i] = SecCertificateCreateWithData (IntPtr.Zero, cfDataPtrs [i]);
if (secCerts [i] == IntPtr.Zero)
return SecTrustResult.Deny;
}
certArray = FromIntPtrs (secCerts);
host = CFStringCreateWithCharacters (IntPtr.Zero, hostName, (IntPtr) hostName.Length);
sslsecpolicy = SecPolicyCreateSSL (true, host);
int code = SecTrustCreateWithCertificates (certArray, sslsecpolicy, out sectrust);
if (code == 0)
code = SecTrustEvaluate (sectrust, out result);
return result;
} finally {
for (int i = 0; i < certCount; i++)
if (cfDataPtrs [i] != IntPtr.Zero)
CFRelease (cfDataPtrs [i]);
if (certArray != IntPtr.Zero)
CFRelease (certArray);
for (int i = 0; i < certCount; i++)
if (secCerts [i] != IntPtr.Zero)
CFRelease (secCerts [i]);
if (sslsecpolicy != IntPtr.Zero)
CFRelease (sslsecpolicy);
if (host != IntPtr.Zero)
CFRelease (host);
if (sectrust != IntPtr.Zero)
CFRelease (sectrust);
}
}
}
}
#endif

View File

@@ -0,0 +1,41 @@
//
// OpenFlags.cs - System.Security.Cryptography.X509Certificates.OpenFlags
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell Inc. (http://www.novell.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 {
[Flags]
public enum OpenFlags {
ReadOnly,
ReadWrite,
MaxAllowed,
OpenExistingOnly = 4,
IncludeArchived = 8
}
}

View File

@@ -0,0 +1,229 @@
//
// PublicKey.cs - System.Security.Cryptography.PublicKey
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
// Tim Coleman (tim@timcoleman.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) Tim Coleman, 2004
// Copyright (C) 2005 Novell, Inc (http://www.novell.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.
//
#if SECURITY_DEP
#if MONOTOUCH || MONODROID
using Mono.Security;
using Mono.Security.Cryptography;
using MSX = Mono.Security.X509;
#else
extern alias MonoSecurity;
using MonoSecurity::Mono.Security;
using MonoSecurity::Mono.Security.Cryptography;
using MSX = MonoSecurity::Mono.Security.X509;
#endif
namespace System.Security.Cryptography.X509Certificates {
public sealed class PublicKey {
private const string rsaOid = "1.2.840.113549.1.1.1";
private const string dsaOid = "1.2.840.10040.4.1";
private AsymmetricAlgorithm _key;
private AsnEncodedData _keyValue;
private AsnEncodedData _params;
private Oid _oid;
static byte[] Empty = new byte [0];
public PublicKey (Oid oid, AsnEncodedData parameters, AsnEncodedData keyValue)
{
if (oid == null)
throw new ArgumentNullException ("oid");
if (parameters == null)
throw new ArgumentNullException ("parameters");
if (keyValue == null)
throw new ArgumentNullException ("keyValue");
_oid = new Oid (oid);
_params = new AsnEncodedData (parameters);
_keyValue = new AsnEncodedData (keyValue);
}
internal PublicKey (MSX.X509Certificate certificate)
{
// note: _key MUSTonly contains the public part of the key
bool export_required = true;
if (certificate.KeyAlgorithm == rsaOid) {
// shortcut export/import in the case the private key isn't available
RSACryptoServiceProvider rcsp = (certificate.RSA as RSACryptoServiceProvider);
if ((rcsp != null) && rcsp.PublicOnly) {
_key = certificate.RSA;
export_required = false;
} else
{
RSAManaged rsam = (certificate.RSA as RSAManaged);
if ((rsam != null) && rsam.PublicOnly) {
_key = certificate.RSA;
export_required = false;
}
}
if (export_required) {
RSAParameters rsap = certificate.RSA.ExportParameters (false);
_key = RSA.Create ();
(_key as RSA).ImportParameters (rsap);
}
} else {
// shortcut export/import in the case the private key isn't available
DSACryptoServiceProvider dcsp = (certificate.DSA as DSACryptoServiceProvider);
if ((dcsp != null) && dcsp.PublicOnly) {
_key = certificate.DSA;
export_required = false;
}
// note: DSAManaged isn't available in Mono.Security due to a bug in Fx 1.x
if (export_required) {
DSAParameters rsap = certificate.DSA.ExportParameters (false);
_key = DSA.Create ();
(_key as DSA).ImportParameters (rsap);
}
}
_oid = new Oid (certificate.KeyAlgorithm);
_keyValue = new AsnEncodedData (_oid, certificate.PublicKey);
_params = new AsnEncodedData (_oid, certificate.KeyAlgorithmParameters ?? Empty);
}
// properties
public AsnEncodedData EncodedKeyValue {
get { return _keyValue; }
}
public AsnEncodedData EncodedParameters {
get { return _params; }
}
public AsymmetricAlgorithm Key {
get {
if (_key == null) {
switch (_oid.Value) {
case rsaOid:
_key = DecodeRSA (_keyValue.RawData);
break;
case dsaOid:
_key = DecodeDSA (_keyValue.RawData, _params.RawData);
break;
default:
string msg = Locale.GetText ("Cannot decode public key from unknown OID '{0}'.", _oid.Value);
throw new NotSupportedException (msg);
}
}
return _key;
}
}
public Oid Oid {
get { return _oid; }
}
// private stuff
static private byte[] GetUnsignedBigInteger (byte[] integer)
{
if (integer [0] != 0x00)
return integer;
// this first byte is added so we're sure it's an unsigned integer
// however we can't feed it into RSAParameters or DSAParameters
int length = integer.Length - 1;
byte[] uinteger = new byte [length];
Buffer.BlockCopy (integer, 1, uinteger, 0, length);
return uinteger;
}
static internal DSA DecodeDSA (byte[] rawPublicKey, byte[] rawParameters)
{
DSAParameters dsaParams = new DSAParameters ();
try {
// for DSA rawPublicKey contains 1 ASN.1 integer - Y
ASN1 pubkey = new ASN1 (rawPublicKey);
if (pubkey.Tag != 0x02)
throw new CryptographicException (Locale.GetText ("Missing DSA Y integer."));
dsaParams.Y = GetUnsignedBigInteger (pubkey.Value);
ASN1 param = new ASN1 (rawParameters);
if ((param == null) || (param.Tag != 0x30) || (param.Count < 3))
throw new CryptographicException (Locale.GetText ("Missing DSA parameters."));
if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02))
throw new CryptographicException (Locale.GetText ("Invalid DSA parameters."));
dsaParams.P = GetUnsignedBigInteger (param [0].Value);
dsaParams.Q = GetUnsignedBigInteger (param [1].Value);
dsaParams.G = GetUnsignedBigInteger (param [2].Value);
}
catch (Exception e) {
string msg = Locale.GetText ("Error decoding the ASN.1 structure.");
throw new CryptographicException (msg, e);
}
DSA dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3);
dsa.ImportParameters (dsaParams);
return dsa;
}
static internal RSA DecodeRSA (byte[] rawPublicKey)
{
RSAParameters rsaParams = new RSAParameters ();
try {
// for RSA rawPublicKey contains 2 ASN.1 integers
// the modulus and the public exponent
ASN1 pubkey = new ASN1 (rawPublicKey);
if (pubkey.Count == 0)
throw new CryptographicException (Locale.GetText ("Missing RSA modulus and exponent."));
ASN1 modulus = pubkey [0];
if ((modulus == null) || (modulus.Tag != 0x02))
throw new CryptographicException (Locale.GetText ("Missing RSA modulus."));
ASN1 exponent = pubkey [1];
if (exponent.Tag != 0x02)
throw new CryptographicException (Locale.GetText ("Missing RSA public exponent."));
rsaParams.Modulus = GetUnsignedBigInteger (modulus.Value);
rsaParams.Exponent = exponent.Value;
}
catch (Exception e) {
string msg = Locale.GetText ("Error decoding the ASN.1 structure.");
throw new CryptographicException (msg, e);
}
int keySize = (rsaParams.Modulus.Length << 3);
RSA rsa = (RSA) new RSACryptoServiceProvider (keySize);
rsa.ImportParameters (rsaParams);
return rsa;
}
}
}
#endif

View File

@@ -0,0 +1,37 @@
//
// StoreLocation.cs - System.Security.Cryptography.X509Certificates.StoreLocation
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell Inc. (http://www.novell.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 {
public enum StoreLocation {
CurrentUser = 1,
LocalMachine = 2
}
}

View File

@@ -0,0 +1,43 @@
//
// StoreName.cs - System.Security.Cryptography.X509Certificates.StoreName
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell Inc. (http://www.novell.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 {
public enum StoreName {
AddressBook = 1,
AuthRoot = 2,
CertificateAuthority = 3,
Disallowed = 4,
My = 5,
Root = 6,
TrustedPeople = 7,
TrustedPublisher = 8
}
}

View File

@@ -0,0 +1,234 @@
//
// System.Security.Cryptography.X509Certificates.X500DistinguishedName
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2006 Novell Inc. (http://www.novell.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.
//
#if SECURITY_DEP
#if MONOTOUCH || MONODROID
using Mono.Security;
using MX = Mono.Security.X509;
#else
extern alias MonoSecurity;
using MonoSecurity::Mono.Security;
using MX = MonoSecurity::Mono.Security.X509;
#endif
using System.Collections;
using System.Text;
namespace System.Security.Cryptography.X509Certificates {
[MonoTODO ("Some X500DistinguishedNameFlags options aren't supported, like DoNotUsePlusSign, DoNotUseQuotes and ForceUTF8Encoding")]
public sealed class X500DistinguishedName : AsnEncodedData {
private const X500DistinguishedNameFlags AllFlags = X500DistinguishedNameFlags.Reversed |
X500DistinguishedNameFlags.UseSemicolons | X500DistinguishedNameFlags.DoNotUsePlusSign |
X500DistinguishedNameFlags.DoNotUseQuotes | X500DistinguishedNameFlags.UseCommas |
X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.UseUTF8Encoding |
X500DistinguishedNameFlags.UseT61Encoding | X500DistinguishedNameFlags.ForceUTF8Encoding;
private string name;
public X500DistinguishedName (AsnEncodedData encodedDistinguishedName)
{
if (encodedDistinguishedName == null)
throw new ArgumentNullException ("encodedDistinguishedName");
RawData = encodedDistinguishedName.RawData;
if (RawData.Length > 0)
DecodeRawData ();
else
name = String.Empty;
}
public X500DistinguishedName (byte[] encodedDistinguishedName)
{
if (encodedDistinguishedName == null)
throw new ArgumentNullException ("encodedDistinguishedName");
Oid = new Oid ();
RawData = encodedDistinguishedName;
if (encodedDistinguishedName.Length > 0)
DecodeRawData ();
else
name = String.Empty;
}
public X500DistinguishedName (string distinguishedName)
: this (distinguishedName, X500DistinguishedNameFlags.Reversed)
{
}
public X500DistinguishedName (string distinguishedName, X500DistinguishedNameFlags flag)
{
if (distinguishedName == null)
throw new ArgumentNullException ("distinguishedName");
if ((flag != 0) && ((flag & AllFlags) == 0))
throw new ArgumentException ("flag");
Oid = new Oid ();
if (distinguishedName.Length == 0) {
// empty (0x00) ASN.1 sequence (0x30)
RawData = new byte [2] { 0x30, 0x00 };
DecodeRawData ();
} else {
var dn = MX.X501.FromString (distinguishedName);
if ((flag & X500DistinguishedNameFlags.Reversed) != 0) {
ASN1 rdn = new ASN1 (0x30);
for (int i = dn.Count - 1; i >= 0; i--)
rdn.Add (dn [i]);
dn = rdn;
}
RawData = dn.GetBytes ();
if (flag == X500DistinguishedNameFlags.None)
name = distinguishedName;
else
name = Decode (flag);
}
}
public X500DistinguishedName (X500DistinguishedName distinguishedName)
{
if (distinguishedName == null)
throw new ArgumentNullException ("distinguishedName");
Oid = new Oid ();
RawData = distinguishedName.RawData;
name = distinguishedName.name;
}
public string Name {
get { return name; }
}
public string Decode (X500DistinguishedNameFlags flag)
{
if ((flag != 0) && ((flag & AllFlags) == 0))
throw new ArgumentException ("flag");
if (RawData.Length == 0)
return String.Empty;
// Mono.Security reversed isn't the same as fx 2.0 (which is the reverse of 1.x)
bool reversed = ((flag & X500DistinguishedNameFlags.Reversed) != 0);
bool quotes = ((flag & X500DistinguishedNameFlags.DoNotUseQuotes) == 0);
string separator = GetSeparator (flag);
ASN1 rdn = new ASN1 (RawData);
return MX.X501.ToString (rdn, reversed, separator, quotes);
}
public override string Format (bool multiLine)
{
if (multiLine) {
string s = Decode (X500DistinguishedNameFlags.UseNewLines);
if (s.Length > 0)
return s + Environment.NewLine;
else
return s;
} else {
return Decode (X500DistinguishedNameFlags.UseCommas);
}
}
// private stuff
private static string GetSeparator (X500DistinguishedNameFlags flag)
{
if ((flag & X500DistinguishedNameFlags.UseSemicolons) != 0)
return "; ";
if ((flag & X500DistinguishedNameFlags.UseCommas) != 0)
return ", ";
if ((flag & X500DistinguishedNameFlags.UseNewLines) != 0)
return Environment.NewLine;
return ", "; //default
}
// decode the DN using the (byte[]) RawData
private void DecodeRawData ()
{
if ((RawData == null) || (RawData.Length < 3)) {
name = String.Empty;
return;
}
ASN1 sequence = new ASN1 (RawData);
name = MX.X501.ToString (sequence, true, ", ", true);
}
private static string Canonize (string s)
{
int i = s.IndexOf ('=') + 1;
StringBuilder r = new StringBuilder (s.Substring (0, i));
// skip any white space starting the value
while (i < s.Length && Char.IsWhiteSpace (s, i))
i++;
// ensure we skip white spaces at the end of the value
s = s.TrimEnd ();
// keep track of internal multiple spaces
bool space = false;
for (; i < s.Length; i++) {
if (space) {
space = Char.IsWhiteSpace (s, i);
if (space)
continue;
}
if (Char.IsWhiteSpace (s, i))
space = true;
r.Append (Char.ToUpperInvariant (s[i]));
}
return r.ToString ();
}
// of all X500DistinguishedNameFlags flags nothing can do a "correct" comparison :|
internal static bool AreEqual (X500DistinguishedName name1, X500DistinguishedName name2)
{
if (name1 == null)
return (name2 == null);
if (name2 == null)
return false;
X500DistinguishedNameFlags flags = X500DistinguishedNameFlags.UseNewLines | X500DistinguishedNameFlags.DoNotUseQuotes;
string[] split = new string[] { Environment.NewLine };
string[] parts1 = name1.Decode (flags).Split (split, StringSplitOptions.RemoveEmptyEntries);
string[] parts2 = name2.Decode (flags).Split (split, StringSplitOptions.RemoveEmptyEntries);
if (parts1.Length != parts2.Length)
return false;
for (int i = 0; i < parts1.Length; i++) {
if (Canonize (parts1[i]) != Canonize (parts2[i]))
return false;
}
return true;
}
}
}
#endif

View File

@@ -0,0 +1,45 @@
//
// System.Security.Cryptography.X509Certificates.X500DistinguishedNameFlags
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004-2005 Novell Inc. (http://www.novell.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 {
[Flags]
public enum X500DistinguishedNameFlags {
None = 0,
Reversed = 1,
UseSemicolons = 16,
DoNotUsePlusSign = 32,
DoNotUseQuotes = 64,
UseCommas = 128,
UseNewLines = 256,
UseUTF8Encoding = 4096,
UseT61Encoding = 8192,
ForceUTF8Encoding = 16384
}
}

View File

@@ -0,0 +1,236 @@
//
// System.Security.Cryptography.X509BasicConstraintsExtension
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
// Tim Coleman (tim@timcoleman.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) Tim Coleman, 2004
// Copyright (C) 2005 Novell, Inc (http://www.novell.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.
//
#if SECURITY_DEP
#if MONOTOUCH || MONODROID
using Mono.Security;
#else
extern alias MonoSecurity;
using MonoSecurity::Mono.Security;
#endif
using System.Text;
namespace System.Security.Cryptography.X509Certificates {
public sealed class X509BasicConstraintsExtension : X509Extension {
internal const string oid = "2.5.29.19";
internal const string friendlyName = "Basic Constraints";
private bool _certificateAuthority;
private bool _hasPathLengthConstraint;
private int _pathLengthConstraint;
private AsnDecodeStatus _status;
// constructors
public X509BasicConstraintsExtension ()
{
_oid = new Oid (oid, friendlyName);
}
public X509BasicConstraintsExtension (AsnEncodedData encodedBasicConstraints, bool critical)
{
// ignore the Oid provided by encodedKeyUsage (our rules!)
_oid = new Oid (oid, friendlyName);
_raw = encodedBasicConstraints.RawData;
base.Critical = critical;
_status = Decode (this.RawData);
}
public X509BasicConstraintsExtension (bool certificateAuthority, bool hasPathLengthConstraint, int pathLengthConstraint, bool critical)
{
if (hasPathLengthConstraint) {
if (pathLengthConstraint < 0)
throw new ArgumentOutOfRangeException ("pathLengthConstraint");
_pathLengthConstraint = pathLengthConstraint;
}
_hasPathLengthConstraint = hasPathLengthConstraint;
_certificateAuthority = certificateAuthority;
_oid = new Oid (oid, friendlyName);
base.Critical = critical;
RawData = Encode ();
}
// properties
public bool CertificateAuthority {
get {
switch (_status) {
case AsnDecodeStatus.Ok:
case AsnDecodeStatus.InformationNotAvailable:
return _certificateAuthority;
default:
throw new CryptographicException ("Badly encoded extension.");
}
}
}
public bool HasPathLengthConstraint {
get {
switch (_status) {
case AsnDecodeStatus.Ok:
case AsnDecodeStatus.InformationNotAvailable:
return _hasPathLengthConstraint;
default:
throw new CryptographicException ("Badly encoded extension.");
}
}
}
public int PathLengthConstraint {
get {
switch (_status) {
case AsnDecodeStatus.Ok:
case AsnDecodeStatus.InformationNotAvailable:
return _pathLengthConstraint;
default:
throw new CryptographicException ("Badly encoded extension.");
}
}
}
// methods
public override void CopyFrom (AsnEncodedData asnEncodedData)
{
if (asnEncodedData == null)
throw new ArgumentNullException ("asnEncodedData");
X509Extension ex = (asnEncodedData as X509Extension);
if (ex == null)
throw new ArgumentException (Locale.GetText ("Wrong type."), "asnEncodedData");
if (ex._oid == null)
_oid = new Oid (oid, friendlyName);
else
_oid = new Oid (ex._oid);
RawData = ex.RawData;
base.Critical = ex.Critical;
// and we deal with the rest later
_status = Decode (this.RawData);
}
// internal
internal AsnDecodeStatus Decode (byte[] extension)
{
if ((extension == null) || (extension.Length == 0))
return AsnDecodeStatus.BadAsn;
if (extension [0] != 0x30)
return AsnDecodeStatus.BadTag;
if (extension.Length < 3) {
if (!((extension.Length == 2) && (extension [1] == 0x00)))
return AsnDecodeStatus.BadLength;
}
try {
ASN1 sequence = new ASN1 (extension);
int n = 0;
ASN1 a = sequence [n++];
if ((a != null) && (a.Tag == 0x01)) {
_certificateAuthority = (a.Value [0] == 0xFF);
a = sequence [n++];
}
if ((a != null) && (a.Tag == 0x02)) {
_hasPathLengthConstraint = true;
_pathLengthConstraint = ASN1Convert.ToInt32 (a);
}
}
catch {
return AsnDecodeStatus.BadAsn;
}
return AsnDecodeStatus.Ok;
}
internal byte[] Encode ()
{
ASN1 ex = new ASN1 (0x30);
if (_certificateAuthority)
ex.Add (new ASN1 (0x01, new byte[] { 0xFF }));
if (_hasPathLengthConstraint) {
// MS encodes the 0 (pathLengthConstraint is OPTIONAL)
// and in a long form (02 00 versus 02 01 00)
if (_pathLengthConstraint == 0)
ex.Add (new ASN1 (0x02, new byte[] { 0x00 }));
else
ex.Add (ASN1Convert.FromInt32 (_pathLengthConstraint));
}
return ex.GetBytes ();
}
internal override string ToString (bool multiLine)
{
switch (_status) {
case AsnDecodeStatus.BadAsn:
return String.Empty;
case AsnDecodeStatus.BadTag:
case AsnDecodeStatus.BadLength:
return FormatUnkownData (_raw);
case AsnDecodeStatus.InformationNotAvailable:
return "Information Not Available";
}
if (_oid.Value != oid)
return String.Format ("Unknown Key Usage ({0})", _oid.Value);
StringBuilder sb = new StringBuilder ();
sb.Append ("Subject Type=");
if (_certificateAuthority)
sb.Append ("CA");
else
sb.Append ("End Entity");
if (multiLine)
sb.Append (Environment.NewLine);
else
sb.Append (", ");
sb.Append ("Path Length Constraint=");
if (_hasPathLengthConstraint)
sb.Append (_pathLengthConstraint);
else
sb.Append ("None");
if (multiLine)
sb.Append (Environment.NewLine);
return sb.ToString ();
}
}
}
#endif

View File

@@ -0,0 +1,408 @@
//
// System.Security.Cryptography.X509Certificates.X509Certificate2Collection class
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
// Tim Coleman (tim@timcoleman.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) Tim Coleman, 2004
// Copyright (C) 2005, 2006 Novell Inc. (http://www.novell.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.
//
#if SECURITY_DEP
using System.Collections;
using System.Globalization;
namespace System.Security.Cryptography.X509Certificates {
public class X509Certificate2Collection : X509CertificateCollection {
// constructors
public X509Certificate2Collection ()
{
}
public X509Certificate2Collection (X509Certificate2Collection certificates)
{
AddRange (certificates);
}
public X509Certificate2Collection (X509Certificate2 certificate)
{
Add (certificate);
}
public X509Certificate2Collection (X509Certificate2[] certificates)
{
AddRange (certificates);
}
// properties
public new X509Certificate2 this [int index] {
get {
if (index < 0)
throw new ArgumentOutOfRangeException ("negative index");
if (index >= InnerList.Count)
throw new ArgumentOutOfRangeException ("index >= Count");
return (X509Certificate2) InnerList [index];
}
set { InnerList [index] = value; }
}
// methods
public int Add (X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
return InnerList.Add (certificate);
}
[MonoTODO ("Method isn't transactional (like documented)")]
public void AddRange (X509Certificate2[] certificates)
{
if (certificates == null)
throw new ArgumentNullException ("certificates");
for (int i=0; i < certificates.Length; i++)
InnerList.Add (certificates [i]);
}
[MonoTODO ("Method isn't transactional (like documented)")]
public void AddRange (X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException ("certificates");
InnerList.AddRange (certificates);
}
public bool Contains (X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
foreach (X509Certificate2 c in InnerList) {
if (c.Equals (certificate))
return true;
}
return false;
}
[MonoTODO ("only support X509ContentType.Cert")]
public byte[] Export (X509ContentType contentType)
{
return Export (contentType, null);
}
[MonoTODO ("only support X509ContentType.Cert")]
public byte[] Export (X509ContentType contentType, string password)
{
switch (contentType) {
case X509ContentType.Cert:
case X509ContentType.Pfx: // this includes Pkcs12
case X509ContentType.SerializedCert:
// if multiple certificates are present we only export the last one
if (Count > 0)
return this [Count - 1].Export (contentType, password);
break;
case X509ContentType.Pkcs7:
// TODO
break;
case X509ContentType.SerializedStore:
// TODO
break;
default:
// this includes Authenticode, Unknown and bad values
string msg = Locale.GetText ("Cannot export certificate(s) to the '{0}' format", contentType);
throw new CryptographicException (msg);
}
return null;
}
static string[] newline_split = new string[] { Environment.NewLine };
[MonoTODO ("Does not support X509FindType.FindByTemplateName, FindByApplicationPolicy and FindByCertificatePolicy")]
public X509Certificate2Collection Find (X509FindType findType, object findValue, bool validOnly)
{
if (findValue == null)
throw new ArgumentNullException ("findValue");
string str = String.Empty;
string oid = String.Empty;
X509KeyUsageFlags ku = X509KeyUsageFlags.None;
DateTime dt = DateTime.MinValue;
switch (findType) {
case X509FindType.FindByThumbprint:
case X509FindType.FindBySubjectName:
case X509FindType.FindBySubjectDistinguishedName:
case X509FindType.FindByIssuerName:
case X509FindType.FindByIssuerDistinguishedName:
case X509FindType.FindBySerialNumber:
case X509FindType.FindByTemplateName:
case X509FindType.FindBySubjectKeyIdentifier:
try {
str = (string) findValue;
}
catch (Exception e) {
string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.",
findValue.GetType (), "string");
throw new CryptographicException (msg, e);
}
break;
case X509FindType.FindByApplicationPolicy:
case X509FindType.FindByCertificatePolicy:
case X509FindType.FindByExtension:
try {
oid = (string) findValue;
}
catch (Exception e) {
string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.",
findValue.GetType (), "X509KeyUsageFlags");
throw new CryptographicException (msg, e);
}
// OID validation
try {
CryptoConfig.EncodeOID (oid);
}
catch (CryptographicUnexpectedOperationException) {
string msg = Locale.GetText ("Invalid OID value '{0}'.", oid);
throw new ArgumentException ("findValue", msg);
}
break;
case X509FindType.FindByKeyUsage:
try {
ku = (X509KeyUsageFlags) findValue;
}
catch (Exception e) {
string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.",
findValue.GetType (), "X509KeyUsageFlags");
throw new CryptographicException (msg, e);
}
break;
case X509FindType.FindByTimeValid:
case X509FindType.FindByTimeNotYetValid:
case X509FindType.FindByTimeExpired:
try {
dt = (DateTime) findValue;
}
catch (Exception e) {
string msg = Locale.GetText ("Invalid find value type '{0}', expected '{1}'.",
findValue.GetType (), "X509DateTime");
throw new CryptographicException (msg,e );
}
break;
default:
{
string msg = Locale.GetText ("Invalid find type '{0}'.", findType);
throw new CryptographicException (msg);
}
}
CultureInfo cinv = CultureInfo.InvariantCulture;
X509Certificate2Collection results = new X509Certificate2Collection ();
foreach (X509Certificate2 x in InnerList) {
bool value_match = false;
switch (findType) {
case X509FindType.FindByThumbprint:
// works with Thumbprint, GetCertHashString in both normal (upper) and lower case
value_match = ((String.Compare (str, x.Thumbprint, true, cinv) == 0) ||
(String.Compare (str, x.GetCertHashString (), true, cinv) == 0));
break;
case X509FindType.FindBySubjectName:
string [] names = x.SubjectName.Format (true).Split (newline_split, StringSplitOptions.RemoveEmptyEntries);
foreach (string name in names) {
int pos = name.IndexOf ('=');
value_match = (name.IndexOf (str, pos, StringComparison.InvariantCultureIgnoreCase) >= 0);
if (value_match)
break;
}
break;
case X509FindType.FindBySubjectDistinguishedName:
value_match = (String.Compare (str, x.Subject, true, cinv) == 0);
break;
case X509FindType.FindByIssuerName:
string iname = x.GetNameInfo (X509NameType.SimpleName, true);
value_match = (iname.IndexOf (str, StringComparison.InvariantCultureIgnoreCase) >= 0);
break;
case X509FindType.FindByIssuerDistinguishedName:
value_match = (String.Compare (str, x.Issuer, true, cinv) == 0);
break;
case X509FindType.FindBySerialNumber:
value_match = (String.Compare (str, x.SerialNumber, true, cinv) == 0);
break;
case X509FindType.FindByTemplateName:
// TODO - find a valid test case
break;
case X509FindType.FindBySubjectKeyIdentifier:
X509SubjectKeyIdentifierExtension ski = (x.Extensions ["2.5.29.14"] as X509SubjectKeyIdentifierExtension);
if (ski != null) {
value_match = (String.Compare (str, ski.SubjectKeyIdentifier, true, cinv) == 0);
}
break;
case X509FindType.FindByApplicationPolicy:
// note: include when no extensions are present (even if v3)
value_match = (x.Extensions.Count == 0);
// TODO - find test case with extension
break;
case X509FindType.FindByCertificatePolicy:
// TODO - find test case with extension
break;
case X509FindType.FindByExtension:
value_match = (x.Extensions [oid] != null);
break;
case X509FindType.FindByKeyUsage:
X509KeyUsageExtension kue = (x.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
if (kue == null) {
// key doesn't have any hard coded limitations
// note: MS doesn't check for ExtendedKeyUsage
value_match = true;
} else {
value_match = ((kue.KeyUsages & ku) == ku);
}
break;
case X509FindType.FindByTimeValid:
value_match = ((dt >= x.NotBefore) && (dt <= x.NotAfter));
break;
case X509FindType.FindByTimeNotYetValid:
value_match = (dt < x.NotBefore);
break;
case X509FindType.FindByTimeExpired:
value_match = (dt > x.NotAfter);
break;
}
if (!value_match)
continue;
if (validOnly) {
try {
if (x.Verify ())
results.Add (x);
}
catch {
}
} else {
results.Add (x);
}
}
return results;
}
public new X509Certificate2Enumerator GetEnumerator ()
{
return new X509Certificate2Enumerator (this);
}
[MonoTODO ("same limitations as X509Certificate2.Import")]
public void Import (byte[] rawData)
{
// FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
X509Certificate2 cert = new X509Certificate2 ();
cert.Import (rawData);
Add (cert);
}
[MonoTODO ("same limitations as X509Certificate2.Import")]
public void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
// FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
X509Certificate2 cert = new X509Certificate2 ();
cert.Import (rawData, password, keyStorageFlags);
Add (cert);
}
[MonoTODO ("same limitations as X509Certificate2.Import")]
public void Import (string fileName)
{
// FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
X509Certificate2 cert = new X509Certificate2 ();
cert.Import (fileName);
Add (cert);
}
[MonoTODO ("same limitations as X509Certificate2.Import")]
public void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
// FIXME: can it import multiple certificates, e.g. a pkcs7 file ?
X509Certificate2 cert = new X509Certificate2 ();
cert.Import (fileName, password, keyStorageFlags);
Add (cert);
}
public void Insert (int index, X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
if (index < 0)
throw new ArgumentOutOfRangeException ("negative index");
if (index >= InnerList.Count)
throw new ArgumentOutOfRangeException ("index >= Count");
InnerList.Insert (index, certificate);
}
public void Remove (X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
for (int i=0; i < InnerList.Count; i++) {
X509Certificate c = (X509Certificate) InnerList [i];
if (c.Equals (certificate)) {
InnerList.RemoveAt (i);
// only first instance is removed
return;
}
}
}
[MonoTODO ("Method isn't transactional (like documented)")]
public void RemoveRange (X509Certificate2[] certificates)
{
if (certificates == null)
throw new ArgumentNullException ("certificate");
foreach (X509Certificate2 x in certificates)
Remove (x);
}
[MonoTODO ("Method isn't transactional (like documented)")]
public void RemoveRange (X509Certificate2Collection certificates)
{
if (certificates == null)
throw new ArgumentNullException ("certificate");
foreach (X509Certificate2 x in certificates)
Remove (x);
}
}
}
#endif

View File

@@ -0,0 +1,81 @@
//
// System.Security.Cryptography.X509Certificates.X509Certificate2Enumerator class
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2005 Novell Inc. (http://www.novell.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.
//
#if SECURITY_DEP
using System.Collections;
namespace System.Security.Cryptography.X509Certificates {
public sealed class X509Certificate2Enumerator : IEnumerator {
private IEnumerator enumerator;
internal X509Certificate2Enumerator (X509Certificate2Collection collection)
{
enumerator = ((IEnumerable) collection).GetEnumerator ();
}
// properties
public X509Certificate2 Current {
get { return (X509Certificate2) enumerator.Current; }
}
// methods
public bool MoveNext ()
{
return enumerator.MoveNext ();
}
public void Reset ()
{
enumerator.Reset ();
}
// IEnumerator
object IEnumerator.Current {
get { return enumerator.Current; }
}
bool IEnumerator.MoveNext ()
{
return enumerator.MoveNext ();
}
void IEnumerator.Reset ()
{
enumerator.Reset ();
}
}
}
#endif

View File

@@ -0,0 +1,207 @@
//
// System.Security.Cryptography.X509Certificates.X509CertificateCollection
//
// Authors:
// Lawrence Pit (loz@cable.a2000.nl)
// Sebastien Pouliot (spouliot@motus.com)
//
// Copyright (C) 2004 Novell (http://www.novell.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.Collections;
using System.Globalization;
using System.Security.Cryptography;
namespace System.Security.Cryptography.X509Certificates {
[Serializable]
public class X509CertificateCollection : CollectionBase {
public X509CertificateCollection ()
{
}
public X509CertificateCollection (X509Certificate [] value)
{
AddRange (value);
}
public X509CertificateCollection (X509CertificateCollection value)
{
AddRange (value);
}
// Properties
public X509Certificate this [int index] {
get { return (X509Certificate) InnerList [index]; }
set { InnerList [index] = value; }
}
// Methods
public int Add (X509Certificate value)
{
if (value == null)
throw new ArgumentNullException ("value");
return InnerList.Add (value);
}
public void AddRange (X509Certificate [] value)
{
if (value == null)
throw new ArgumentNullException ("value");
for (int i = 0; i < value.Length; i++)
InnerList.Add (value [i]);
}
public void AddRange (X509CertificateCollection value)
{
if (value == null)
throw new ArgumentNullException ("value");
for (int i = 0; i < value.InnerList.Count; i++)
InnerList.Add (value [i]);
}
public bool Contains (X509Certificate value)
{
if (value == null)
return false;
byte[] hash = value.GetCertHash ();
for (int i=0; i < InnerList.Count; i++) {
X509Certificate x509 = (X509Certificate) InnerList [i];
if (Compare (x509.GetCertHash (), hash))
return true;
}
return false;
}
public void CopyTo (X509Certificate[] array, int index)
{
InnerList.CopyTo (array, index);
}
public new X509CertificateEnumerator GetEnumerator ()
{
return new X509CertificateEnumerator (this);
}
public override int GetHashCode ()
{
return InnerList.GetHashCode ();
}
public int IndexOf (X509Certificate value)
{
return InnerList.IndexOf (value);
}
public void Insert (int index, X509Certificate value)
{
InnerList.Insert (index, value);
}
public void Remove (X509Certificate value)
{
if (value == null)
throw new ArgumentNullException ("value");
if (IndexOf (value) == -1) {
throw new ArgumentException ("value",
Locale.GetText ("Not part of the collection."));
}
InnerList.Remove (value);
}
// private stuff
private bool Compare (byte[] array1, byte[] array2)
{
if ((array1 == null) && (array2 == null))
return true;
if ((array1 == null) || (array2 == null))
return false;
if (array1.Length != array2.Length)
return false;
for (int i=0; i < array1.Length; i++) {
if (array1 [i] != array2 [i])
return false;
}
return true;
}
// Inner Class
public class X509CertificateEnumerator : IEnumerator {
private IEnumerator enumerator;
// Constructors
public X509CertificateEnumerator (X509CertificateCollection mappings)
{
enumerator = ((IEnumerable) mappings).GetEnumerator ();
}
// Properties
public X509Certificate Current {
get { return (X509Certificate) enumerator.Current; }
}
object IEnumerator.Current {
get { return enumerator.Current; }
}
// Methods
bool IEnumerator.MoveNext ()
{
return enumerator.MoveNext ();
}
void IEnumerator.Reset ()
{
enumerator.Reset ();
}
public bool MoveNext ()
{
return enumerator.MoveNext ();
}
public void Reset ()
{
enumerator.Reset ();
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,135 @@
//
// X509ChainElement.cs - System.Security.Cryptography.X509Certificates.X509ChainElement
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2005-2006 Novell Inc. (http://www.novell.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.
//
#if SECURITY_DEP
using Mono.Security.X509;
namespace System.Security.Cryptography.X509Certificates {
public class X509ChainElement {
private X509Certificate2 certificate;
private X509ChainStatus[] status;
private string info;
private X509ChainStatusFlags compressed_status_flags;
// constructors
// only accessible from X509Chain.ChainElements
internal X509ChainElement (X509Certificate2 certificate)
{
this.certificate = certificate;
// so far String.Empty is the only thing I've seen.
// The interesting stuff is inside X509ChainStatus.Information
info = String.Empty;
}
// properties
public X509Certificate2 Certificate {
get { return certificate; }
}
public X509ChainStatus[] ChainElementStatus {
get { return status; }
}
public string Information {
get { return info; }
}
// private stuff
internal X509ChainStatusFlags StatusFlags {
get { return compressed_status_flags; }
set { compressed_status_flags = value; }
}
private int Count (X509ChainStatusFlags flags)
{
int size = 0;
int n = 0;
int f = (int) flags;
int m = 0x1;
while (n++ < 32) {
if ((f & m) == m)
size++;
m <<= 1;
}
return size;
}
private void Set (X509ChainStatus[] status, ref int position, X509ChainStatusFlags flags, X509ChainStatusFlags mask)
{
if ((flags & mask) != 0) {
status [position].Status = mask;
status [position].StatusInformation = X509ChainStatus.GetInformation (mask);
position++;
}
}
internal void UncompressFlags ()
{
if (compressed_status_flags == X509ChainStatusFlags.NoError) {
status = new X509ChainStatus [0];
} else {
int size = Count (compressed_status_flags);
status = new X509ChainStatus [size];
int n = 0;
// process every possible error
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.UntrustedRoot);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.NotTimeValid);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.NotTimeNested);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.Revoked);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.NotSignatureValid);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.NotValidForUsage);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.RevocationStatusUnknown);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.Cyclic);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.InvalidExtension);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.InvalidPolicyConstraints);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.InvalidBasicConstraints);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.InvalidNameConstraints);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.HasNotSupportedNameConstraint);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.HasNotDefinedNameConstraint);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.HasNotPermittedNameConstraint);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.HasExcludedNameConstraint);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.PartialChain);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.CtlNotTimeValid);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.CtlNotSignatureValid);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.CtlNotValidForUsage);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.OfflineRevocation);
Set (status, ref n, compressed_status_flags, X509ChainStatusFlags.NoIssuanceChainPolicy);
}
}
}
}
#endif

View File

@@ -0,0 +1,111 @@
//
// X509ChainElementCollection.cs - System.Security.Cryptography.X509Certificates.X509ChainElementCollection
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2006 Novell Inc. (http://www.novell.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.
//
#if SECURITY_DEP
using System.Collections;
namespace System.Security.Cryptography.X509Certificates {
public sealed class X509ChainElementCollection : ICollection, IEnumerable {
private ArrayList _list;
// constructors
// only accessible from X509Chain
internal X509ChainElementCollection ()
{
_list = new ArrayList ();
}
// properties
public int Count {
get { return _list.Count; }
}
public bool IsSynchronized {
get { return _list.IsSynchronized; }
}
public X509ChainElement this [int index] {
get { return (X509ChainElement) _list [index]; }
}
public object SyncRoot {
get { return _list.SyncRoot; }
}
// methods
public void CopyTo (X509ChainElement[] array, int index)
{
_list.CopyTo ((Array)array, index);
}
void ICollection.CopyTo (Array array, int index)
{
_list.CopyTo (array, index);
}
public X509ChainElementEnumerator GetEnumerator ()
{
return new X509ChainElementEnumerator (_list);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return new X509ChainElementEnumerator (_list);
}
// private stuff
internal void Add (X509Certificate2 certificate)
{
_list.Add (new X509ChainElement (certificate));
}
internal void Clear ()
{
_list.Clear ();
}
internal bool Contains (X509Certificate2 certificate)
{
for (int i=0; i < _list.Count; i++) {
if (certificate.Equals (( _list [i] as X509ChainElement).Certificate))
return true;
}
return false;
}
}
}
#endif

View File

@@ -0,0 +1,72 @@
//
// X509ChainElementEnumerator.cs - System.Security.Cryptography.X509Certificates.X509ChainElementEnumerator
//
// Author:
// Sebastien Pouliot (spouliot@motus.com)
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.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.
//
#if SECURITY_DEP
using System.Collections;
namespace System.Security.Cryptography.X509Certificates {
// Note: Match the definition of framework version 1.2.3400.0 on http://longhorn.msdn.microsoft.com
public sealed class X509ChainElementEnumerator : IEnumerator {
private IEnumerator enumerator;
internal X509ChainElementEnumerator (IEnumerable enumerable)
{
enumerator = enumerable.GetEnumerator ();
}
// properties
public X509ChainElement Current {
get { return (X509ChainElement) enumerator.Current; }
}
object IEnumerator.Current {
get { return enumerator.Current; }
}
// methods
public bool MoveNext ()
{
return enumerator.MoveNext ();
}
public void Reset()
{
enumerator.Reset ();
}
}
}
#endif

View File

@@ -0,0 +1,119 @@
//
// System.Security.Cryptography.X509Certificates.X509ChainPolicy class
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2005-2006 Novell Inc. (http://www.novell.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.
//
#if SECURITY_DEP
namespace System.Security.Cryptography.X509Certificates {
public sealed class X509ChainPolicy {
private OidCollection apps;
private OidCollection cert;
private X509Certificate2Collection store;
private X509RevocationFlag rflag;
private X509RevocationMode mode;
private TimeSpan timeout;
private X509VerificationFlags vflags;
private DateTime vtime;
// constructors
public X509ChainPolicy ()
{
Reset ();
}
// properties
public OidCollection ApplicationPolicy {
get { return apps; }
}
public OidCollection CertificatePolicy {
get { return cert; }
}
public X509Certificate2Collection ExtraStore {
get { return store; }
}
public X509RevocationFlag RevocationFlag {
get { return rflag; }
set {
if ((value < X509RevocationFlag.EndCertificateOnly) || (value > X509RevocationFlag.ExcludeRoot))
throw new ArgumentException ("RevocationFlag");
rflag = value;
}
}
public X509RevocationMode RevocationMode {
get { return mode; }
set {
if ((value < X509RevocationMode.NoCheck) || (value > X509RevocationMode.Offline))
throw new ArgumentException ("RevocationMode");
mode = value;
}
}
public TimeSpan UrlRetrievalTimeout {
get { return timeout; }
set { timeout = value; }
}
public X509VerificationFlags VerificationFlags {
get { return vflags; }
set {
if ((value | X509VerificationFlags.AllFlags) != X509VerificationFlags.AllFlags)
throw new ArgumentException ("VerificationFlags");
vflags = value;
}
}
public DateTime VerificationTime {
get { return vtime; }
set { vtime = value; }
}
// methods
public void Reset ()
{
apps = new OidCollection ();
cert = new OidCollection ();
store = new X509Certificate2Collection ();
rflag = X509RevocationFlag.ExcludeRoot;
mode = X509RevocationMode.Online;
timeout = TimeSpan.Zero;
vflags = X509VerificationFlags.NoFlag;
vtime = DateTime.Now;
}
}
}
#endif

View File

@@ -0,0 +1,95 @@
//
// X509ChainStatus.cs - System.Security.Cryptography.X509Certificates.X509ChainStatus
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2006 Novell Inc. (http://www.novell.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.
//
#if SECURITY_DEP
namespace System.Security.Cryptography.X509Certificates {
public struct X509ChainStatus {
private X509ChainStatusFlags status;
private string info;
internal X509ChainStatus (X509ChainStatusFlags flag)
{
status = flag;
info = GetInformation (flag);
}
// properties
public X509ChainStatusFlags Status {
get { return status; }
set { status = value; }
}
public string StatusInformation {
get { return info; }
set { info = value; }
}
// private stuff
// note: flags isn't a flag (i.e. multiple values) when used here
static internal string GetInformation (X509ChainStatusFlags flags)
{
switch (flags) {
case X509ChainStatusFlags.NotTimeValid:
case X509ChainStatusFlags.NotTimeNested:
case X509ChainStatusFlags.Revoked:
case X509ChainStatusFlags.NotSignatureValid:
case X509ChainStatusFlags.NotValidForUsage:
case X509ChainStatusFlags.UntrustedRoot:
case X509ChainStatusFlags.RevocationStatusUnknown:
case X509ChainStatusFlags.Cyclic:
case X509ChainStatusFlags.InvalidExtension:
case X509ChainStatusFlags.InvalidPolicyConstraints:
case X509ChainStatusFlags.InvalidBasicConstraints:
case X509ChainStatusFlags.InvalidNameConstraints:
case X509ChainStatusFlags.HasNotSupportedNameConstraint:
case X509ChainStatusFlags.HasNotDefinedNameConstraint:
case X509ChainStatusFlags.HasNotPermittedNameConstraint:
case X509ChainStatusFlags.HasExcludedNameConstraint:
case X509ChainStatusFlags.PartialChain:
case X509ChainStatusFlags.CtlNotTimeValid:
case X509ChainStatusFlags.CtlNotSignatureValid:
case X509ChainStatusFlags.CtlNotValidForUsage:
case X509ChainStatusFlags.OfflineRevocation:
case X509ChainStatusFlags.NoIssuanceChainPolicy:
return Locale.GetText (flags.ToString ()); // FIXME - add a better description
case X509ChainStatusFlags.NoError:
default:
// should never happen
return String.Empty;
}
}
}
}
#endif

View File

@@ -0,0 +1,59 @@
//
// X509ChainStatusFlags.cs - System.Security.Cryptography.X509Certificates.X509ChainStatusFlags
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
//
// (C) 2003 Motus Technologies Inc. (http://www.motus.com)
// Copyright (C) 2004-2005 Novell Inc. (http://www.novell.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 {
[Flags]
public enum X509ChainStatusFlags {
NoError = 0,
NotTimeValid = 1,
NotTimeNested = 2,
Revoked = 4,
NotSignatureValid = 8,
NotValidForUsage = 16,
UntrustedRoot = 32,
RevocationStatusUnknown = 64,
Cyclic = 128,
InvalidExtension = 256,
InvalidPolicyConstraints = 512,
InvalidBasicConstraints = 1024,
InvalidNameConstraints = 2048,
HasNotSupportedNameConstraint = 4096,
HasNotDefinedNameConstraint = 8192,
HasNotPermittedNameConstraint = 16384,
HasExcludedNameConstraint = 32768,
PartialChain = 65536,
CtlNotTimeValid = 131072,
CtlNotSignatureValid = 262144,
CtlNotValidForUsage = 524288,
OfflineRevocation = 16777216,
NoIssuanceChainPolicy = 33554432
}
}

Some files were not shown because too many files have changed in this diff Show More