2 // System.Security.Cryptography.X509Certificate2 class
5 // Sebastien Pouliot <sebastien@ximian.com>
7 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 #if MONOTOUCH || MONODROID
34 using Mono.Security.Cryptography;
35 using MX = Mono.Security.X509;
37 extern alias MonoSecurity;
39 using MonoSecurity::Mono.Security;
40 using MonoSecurity::Mono.Security.Cryptography;
41 using MX = MonoSecurity::Mono.Security.X509;
49 namespace System.Security.Cryptography.X509Certificates {
54 public class X509Certificate2 : X509Certificate {
56 // Used in Mono.Security HttpsClientStream
57 public X509Certificate2 (byte[] rawData)
62 private bool _archived;
63 private X509ExtensionCollection _extensions;
64 private string _name = String.Empty;
65 private string _serial;
66 private PublicKey _publicKey;
67 private X500DistinguishedName issuer_name;
68 private X500DistinguishedName subject_name;
69 private Oid signature_algorithm;
71 private MX.X509Certificate _cert;
73 private static string empty_error = Locale.GetText ("Certificate instance is empty.");
77 public X509Certificate2 ()
82 public X509Certificate2 (byte[] rawData)
84 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
87 public X509Certificate2 (byte[] rawData, string password)
89 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
92 public X509Certificate2 (byte[] rawData, SecureString password)
94 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
97 public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
99 Import (rawData, password, keyStorageFlags);
102 public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
104 Import (rawData, password, keyStorageFlags);
107 public X509Certificate2 (string fileName)
109 Import (fileName, String.Empty, X509KeyStorageFlags.DefaultKeySet);
112 public X509Certificate2 (string fileName, string password)
114 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
117 public X509Certificate2 (string fileName, SecureString password)
119 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
122 public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
124 Import (fileName, password, keyStorageFlags);
127 public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
129 Import (fileName, password, keyStorageFlags);
132 public X509Certificate2 (IntPtr handle) : base (handle)
134 _cert = new MX.X509Certificate (base.GetRawCertData ());
137 public X509Certificate2 (X509Certificate certificate)
140 _cert = new MX.X509Certificate (base.GetRawCertData ());
145 public bool Archived {
148 throw new CryptographicException (empty_error);
153 throw new CryptographicException (empty_error);
158 public X509ExtensionCollection Extensions {
161 throw new CryptographicException (empty_error);
162 if (_extensions == null)
163 _extensions = new X509ExtensionCollection (_cert);
168 public string FriendlyName {
171 throw new CryptographicException (empty_error);
176 throw new CryptographicException (empty_error);
181 // FIXME - Could be more efficient
182 public bool HasPrivateKey {
183 get { return PrivateKey != null; }
186 public X500DistinguishedName IssuerName {
189 throw new CryptographicException (empty_error);
190 if (issuer_name == null)
191 issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
196 public DateTime NotAfter {
199 throw new CryptographicException (empty_error);
200 return _cert.ValidUntil.ToLocalTime ();
204 public DateTime NotBefore {
207 throw new CryptographicException (empty_error);
208 return _cert.ValidFrom.ToLocalTime ();
212 public AsymmetricAlgorithm PrivateKey {
215 throw new CryptographicException (empty_error);
217 if (_cert.RSA != null) {
218 RSACryptoServiceProvider rcsp = _cert.RSA as RSACryptoServiceProvider;
220 return rcsp.PublicOnly ? null : rcsp;
222 RSAManaged rsam = _cert.RSA as RSAManaged;
224 return rsam.PublicOnly ? null : rsam;
226 _cert.RSA.ExportParameters (true);
228 } else if (_cert.DSA != null) {
229 DSACryptoServiceProvider dcsp = _cert.DSA as DSACryptoServiceProvider;
231 return dcsp.PublicOnly ? null : dcsp;
233 _cert.DSA.ExportParameters (true);
243 throw new CryptographicException (empty_error);
245 // allow NULL so we can "forget" the key associated to the certificate
246 // e.g. in case we want to export it in another format (see bug #396620)
250 } else if (value is RSA)
251 _cert.RSA = (RSA) value;
252 else if (value is DSA)
253 _cert.DSA = (DSA) value;
255 throw new NotSupportedException ();
259 public PublicKey PublicKey {
262 throw new CryptographicException (empty_error);
264 if (_publicKey == null) {
266 _publicKey = new PublicKey (_cert);
268 catch (Exception e) {
269 string msg = Locale.GetText ("Unable to decode public key.");
270 throw new CryptographicException (msg, e);
277 public byte[] RawData {
280 throw new CryptographicException (empty_error);
282 return base.GetRawCertData ();
286 public string SerialNumber {
289 throw new CryptographicException (empty_error);
291 if (_serial == null) {
292 StringBuilder sb = new StringBuilder ();
293 byte[] serial = _cert.SerialNumber;
294 for (int i=serial.Length - 1; i >= 0; i--)
295 sb.Append (serial [i].ToString ("X2"));
296 _serial = sb.ToString ();
302 public Oid SignatureAlgorithm {
305 throw new CryptographicException (empty_error);
307 if (signature_algorithm == null)
308 signature_algorithm = new Oid (_cert.SignatureAlgorithm);
309 return signature_algorithm;
313 public X500DistinguishedName SubjectName {
316 throw new CryptographicException (empty_error);
318 if (subject_name == null)
319 subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
324 public string Thumbprint {
325 get { return base.GetCertHashString (); }
331 throw new CryptographicException (empty_error);
332 return _cert.Version;
338 [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
339 public string GetNameInfo (X509NameType nameType, bool forIssuer)
342 case X509NameType.SimpleName:
344 throw new CryptographicException (empty_error);
345 // return CN= or, if missing, the first part of the DN
346 ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
347 ASN1 dn = Find (commonName, sn);
349 return GetValueAsString (dn);
352 ASN1 last_entry = sn [sn.Count - 1];
353 if (last_entry.Count == 0)
355 return GetValueAsString (last_entry [0]);
356 case X509NameType.EmailName:
357 // return the E= part of the DN (if present)
358 ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
360 return GetValueAsString (e);
362 case X509NameType.UpnName:
363 // FIXME - must find/create test case
365 case X509NameType.DnsName:
366 // return the CN= part of the DN (if present)
367 ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
369 return GetValueAsString (cn);
371 case X509NameType.DnsFromAlternativeName:
372 // FIXME - must find/create test case
374 case X509NameType.UrlName:
375 // FIXME - must find/create test case
378 throw new ArgumentException ("nameType");
382 static byte[] commonName = { 0x55, 0x04, 0x03 };
383 static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
385 private ASN1 Find (byte[] oid, ASN1 dn)
391 for (int i = 0; i < dn.Count; i++) {
393 for (int j = 0; j < set.Count; j++) {
398 ASN1 poid = pair [0];
402 if (poid.CompareValue (oid))
409 private string GetValueAsString (ASN1 pair)
414 ASN1 value = pair [1];
415 if ((value.Value == null) || (value.Length == 0))
418 if (value.Tag == 0x1E) {
420 StringBuilder sb = new StringBuilder ();
421 for (int j = 1; j < value.Value.Length; j += 2)
422 sb.Append ((char)value.Value [j]);
423 return sb.ToString ();
425 return Encoding.UTF8.GetString (value.Value);
429 private MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
431 MX.PKCS12 pfx = null;
432 if (string.IsNullOrEmpty (password)) {
434 // Support both unencrypted PKCS#12..
435 pfx = new MX.PKCS12 (rawData, (string)null);
437 // ..and PKCS#12 encrypted with an empty password
438 pfx = new MX.PKCS12 (rawData, string.Empty);
441 pfx = new MX.PKCS12 (rawData, password);
444 if (pfx.Certificates.Count == 0) {
445 // no certificate was found
447 } else if (pfx.Keys.Count == 0) {
448 // no key were found - pick the first certificate
449 return pfx.Certificates [0];
451 // find the certificate that match the first key
452 MX.X509Certificate cert = null;
453 var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
454 string pubkey = keypair.ToXmlString (false);
455 foreach (var c in pfx.Certificates) {
456 if (((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false))) ||
457 ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))) {
463 cert = pfx.Certificates [0]; // no match, pick first certificate without keys
465 cert.RSA = (keypair as RSA);
466 cert.DSA = (keypair as DSA);
472 public override void Import (byte[] rawData)
474 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
477 [MonoTODO ("missing KeyStorageFlags support")]
478 public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
480 MX.X509Certificate cert = null;
481 if (password == null) {
483 cert = new MX.X509Certificate (rawData);
485 catch (Exception e) {
487 cert = ImportPkcs12 (rawData, null);
490 string msg = Locale.GetText ("Unable to decode certificate.");
491 // inner exception is the original (not second) exception
492 throw new CryptographicException (msg, e);
498 cert = ImportPkcs12 (rawData, password);
501 // it's possible to supply a (unrequired/unusued) password
503 cert = new MX.X509Certificate (rawData);
506 // we do not have to fully re-decode the certificate since X509Certificate does not deal with keys
508 base.Import (cert.RawData, (string) null, keyStorageFlags);
509 _cert = cert; // becuase base call will call Reset!
513 [MonoTODO ("SecureString is incomplete")]
514 public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
516 Import (rawData, (string) null, keyStorageFlags);
519 public override void Import (string fileName)
521 byte[] rawData = File.ReadAllBytes (fileName);
522 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
525 [MonoTODO ("missing KeyStorageFlags support")]
526 public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
528 byte[] rawData = File.ReadAllBytes (fileName);
529 Import (rawData, password, keyStorageFlags);
532 [MonoTODO ("SecureString is incomplete")]
533 public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
535 byte[] rawData = File.ReadAllBytes (fileName);
536 Import (rawData, (string)null, keyStorageFlags);
539 public override void Reset ()
544 _name = String.Empty;
549 signature_algorithm = null;
553 public override string ToString ()
556 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
558 return base.ToString (true);
561 public override string ToString (bool verbose)
564 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
566 // the non-verbose X509Certificate2 == verbose X509Certificate
568 return base.ToString (true);
570 string nl = Environment.NewLine;
571 StringBuilder sb = new StringBuilder ();
572 sb.AppendFormat ("[Version]{0} V{1}{0}{0}", nl, Version);
573 sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, Subject);
574 sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, Issuer);
575 sb.AppendFormat ("[Serial Number]{0} {1}{0}{0}", nl, SerialNumber);
576 sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, NotBefore);
577 sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, NotAfter);
578 sb.AppendFormat ("[Thumbprint]{0} {1}{0}{0}", nl, Thumbprint);
579 sb.AppendFormat ("[Signature Algorithm]{0} {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName,
580 SignatureAlgorithm.Value);
582 AsymmetricAlgorithm key = PublicKey.Key;
583 sb.AppendFormat ("[Public Key]{0} Algorithm: ", nl);
589 sb.Append (key.ToString ());
590 sb.AppendFormat ("{0} Length: {1}{0} Key Blob: ", nl, key.KeySize);
591 AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData);
592 sb.AppendFormat ("{0} Parameters: ", nl);
593 AppendBuffer (sb, PublicKey.EncodedParameters.RawData);
596 return sb.ToString ();
599 private static void AppendBuffer (StringBuilder sb, byte[] buffer)
603 for (int i=0; i < buffer.Length; i++) {
604 sb.Append (buffer [i].ToString ("x2"));
605 if (i < buffer.Length - 1)
610 [MonoTODO ("by default this depends on the incomplete X509Chain")]
611 public bool Verify ()
614 throw new CryptographicException (empty_error);
616 X509Chain chain = X509Chain.Create ();
617 if (!chain.Build (this))
619 // TODO - check chain and other stuff ???
625 private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
627 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")]
628 public static X509ContentType GetCertContentType (byte[] rawData)
630 if ((rawData == null) || (rawData.Length == 0))
631 throw new ArgumentException ("rawData");
633 X509ContentType type = X509ContentType.Unknown;
635 ASN1 data = new ASN1 (rawData);
636 if (data.Tag != 0x30) {
637 string msg = Locale.GetText ("Unable to decode certificate.");
638 throw new CryptographicException (msg);
644 if (data.Count == 3) {
645 switch (data [0].Tag) {
647 // SEQUENCE / SEQUENCE / BITSTRING
648 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03))
649 type = X509ContentType.Cert;
652 // INTEGER / SEQUENCE / SEQUENCE
653 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30))
654 type = X509ContentType.Pkcs12;
655 // note: Pfx == Pkcs12
659 // check for PKCS#7 (count unknown but greater than 0)
660 // SEQUENCE / OID (signedData)
661 if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData))
662 type = X509ContentType.Pkcs7;
664 catch (Exception e) {
665 string msg = Locale.GetText ("Unable to decode certificate.");
666 throw new CryptographicException (msg, e);
672 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")]
673 public static X509ContentType GetCertContentType (string fileName)
675 if (fileName == null)
676 throw new ArgumentNullException ("fileName");
677 if (fileName.Length == 0)
678 throw new ArgumentException ("fileName");
680 byte[] data = File.ReadAllBytes (fileName);
681 return GetCertContentType (data);
684 // internal stuff because X509Certificate2 isn't complete enough
685 // (maybe X509Certificate3 will be better?)
687 internal MX.X509Certificate MonoCertificate {
688 get { return _cert; }
692 // HACK - this ensure the type X509Certificate2 and PrivateKey property exists in the build before
693 // Mono.Security.dll is built. This is required to get working client certificate in SSL/TLS
694 public AsymmetricAlgorithm PrivateKey {