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 {
52 public class X509Certificate2 : X509Certificate {
54 // Used in Mono.Security HttpsClientStream
55 public X509Certificate2 (byte[] rawData)
60 private bool _archived;
61 private X509ExtensionCollection _extensions;
62 private string _name = String.Empty;
63 private string _serial;
64 private PublicKey _publicKey;
65 private X500DistinguishedName issuer_name;
66 private X500DistinguishedName subject_name;
67 private Oid signature_algorithm;
69 private MX.X509Certificate _cert;
71 private static string empty_error = Locale.GetText ("Certificate instance is empty.");
75 public X509Certificate2 ()
80 public X509Certificate2 (byte[] rawData)
82 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
85 public X509Certificate2 (byte[] rawData, string password)
87 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
90 public X509Certificate2 (byte[] rawData, SecureString password)
92 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
95 public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
97 Import (rawData, password, keyStorageFlags);
100 public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
102 Import (rawData, password, keyStorageFlags);
105 public X509Certificate2 (string fileName)
107 Import (fileName, String.Empty, X509KeyStorageFlags.DefaultKeySet);
110 public X509Certificate2 (string fileName, string password)
112 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
115 public X509Certificate2 (string fileName, SecureString password)
117 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
120 public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
122 Import (fileName, password, keyStorageFlags);
125 public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
127 Import (fileName, password, keyStorageFlags);
130 public X509Certificate2 (IntPtr handle) : base (handle)
132 _cert = new MX.X509Certificate (base.GetRawCertData ());
135 public X509Certificate2 (X509Certificate certificate)
138 _cert = new MX.X509Certificate (base.GetRawCertData ());
143 public bool Archived {
146 throw new CryptographicException (empty_error);
151 throw new CryptographicException (empty_error);
156 public X509ExtensionCollection Extensions {
159 throw new CryptographicException (empty_error);
160 if (_extensions == null)
161 _extensions = new X509ExtensionCollection (_cert);
166 public string FriendlyName {
169 throw new CryptographicException (empty_error);
174 throw new CryptographicException (empty_error);
179 // FIXME - Could be more efficient
180 public bool HasPrivateKey {
181 get { return PrivateKey != null; }
184 public X500DistinguishedName IssuerName {
187 throw new CryptographicException (empty_error);
188 if (issuer_name == null)
189 issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
194 public DateTime NotAfter {
197 throw new CryptographicException (empty_error);
198 return _cert.ValidUntil.ToLocalTime ();
202 public DateTime NotBefore {
205 throw new CryptographicException (empty_error);
206 return _cert.ValidFrom.ToLocalTime ();
210 public AsymmetricAlgorithm PrivateKey {
213 throw new CryptographicException (empty_error);
215 if (_cert.RSA != null) {
216 RSACryptoServiceProvider rcsp = _cert.RSA as RSACryptoServiceProvider;
218 return rcsp.PublicOnly ? null : rcsp;
220 RSAManaged rsam = _cert.RSA as RSAManaged;
222 return rsam.PublicOnly ? null : rsam;
224 _cert.RSA.ExportParameters (true);
226 } else if (_cert.DSA != null) {
227 DSACryptoServiceProvider dcsp = _cert.DSA as DSACryptoServiceProvider;
229 return dcsp.PublicOnly ? null : dcsp;
231 _cert.DSA.ExportParameters (true);
241 throw new CryptographicException (empty_error);
243 // allow NULL so we can "forget" the key associated to the certificate
244 // e.g. in case we want to export it in another format (see bug #396620)
248 } else if (value is RSA)
249 _cert.RSA = (RSA) value;
250 else if (value is DSA)
251 _cert.DSA = (DSA) value;
253 throw new NotSupportedException ();
257 public PublicKey PublicKey {
260 throw new CryptographicException (empty_error);
262 if (_publicKey == null) {
264 _publicKey = new PublicKey (_cert);
266 catch (Exception e) {
267 string msg = Locale.GetText ("Unable to decode public key.");
268 throw new CryptographicException (msg, e);
275 public byte[] RawData {
278 throw new CryptographicException (empty_error);
280 return base.GetRawCertData ();
284 public string SerialNumber {
287 throw new CryptographicException (empty_error);
289 if (_serial == null) {
290 StringBuilder sb = new StringBuilder ();
291 byte[] serial = _cert.SerialNumber;
292 for (int i=serial.Length - 1; i >= 0; i--)
293 sb.Append (serial [i].ToString ("X2"));
294 _serial = sb.ToString ();
300 public Oid SignatureAlgorithm {
303 throw new CryptographicException (empty_error);
305 if (signature_algorithm == null)
306 signature_algorithm = new Oid (_cert.SignatureAlgorithm);
307 return signature_algorithm;
311 public X500DistinguishedName SubjectName {
314 throw new CryptographicException (empty_error);
316 if (subject_name == null)
317 subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
322 public string Thumbprint {
323 get { return base.GetCertHashString (); }
329 throw new CryptographicException (empty_error);
330 return _cert.Version;
336 [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
337 public string GetNameInfo (X509NameType nameType, bool forIssuer)
340 case X509NameType.SimpleName:
342 throw new CryptographicException (empty_error);
343 // return CN= or, if missing, the first part of the DN
344 ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
345 ASN1 dn = Find (commonName, sn);
347 return GetValueAsString (dn);
350 ASN1 last_entry = sn [sn.Count - 1];
351 if (last_entry.Count == 0)
353 return GetValueAsString (last_entry [0]);
354 case X509NameType.EmailName:
355 // return the E= part of the DN (if present)
356 ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
358 return GetValueAsString (e);
360 case X509NameType.UpnName:
361 // FIXME - must find/create test case
363 case X509NameType.DnsName:
364 // return the CN= part of the DN (if present)
365 ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
367 return GetValueAsString (cn);
369 case X509NameType.DnsFromAlternativeName:
370 // FIXME - must find/create test case
372 case X509NameType.UrlName:
373 // FIXME - must find/create test case
376 throw new ArgumentException ("nameType");
380 static byte[] commonName = { 0x55, 0x04, 0x03 };
381 static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
383 private ASN1 Find (byte[] oid, ASN1 dn)
389 for (int i = 0; i < dn.Count; i++) {
391 for (int j = 0; j < set.Count; j++) {
396 ASN1 poid = pair [0];
400 if (poid.CompareValue (oid))
407 private string GetValueAsString (ASN1 pair)
412 ASN1 value = pair [1];
413 if ((value.Value == null) || (value.Length == 0))
416 if (value.Tag == 0x1E) {
418 StringBuilder sb = new StringBuilder ();
419 for (int j = 1; j < value.Value.Length; j += 2)
420 sb.Append ((char)value.Value [j]);
421 return sb.ToString ();
423 return Encoding.UTF8.GetString (value.Value);
427 private MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
429 MX.PKCS12 pfx = null;
430 if (string.IsNullOrEmpty (password)) {
432 // Support both unencrypted PKCS#12..
433 pfx = new MX.PKCS12 (rawData, (string)null);
435 // ..and PKCS#12 encrypted with an empty password
436 pfx = new MX.PKCS12 (rawData, string.Empty);
439 pfx = new MX.PKCS12 (rawData, password);
442 if (pfx.Certificates.Count == 0) {
443 // no certificate was found
445 } else if (pfx.Keys.Count == 0) {
446 // no key were found - pick the first certificate
447 return pfx.Certificates [0];
449 // find the certificate that match the first key
450 MX.X509Certificate cert = null;
451 var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
452 string pubkey = keypair.ToXmlString (false);
453 foreach (var c in pfx.Certificates) {
454 if (((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false))) ||
455 ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))) {
461 cert = pfx.Certificates [0]; // no match, pick first certificate without keys
463 cert.RSA = (keypair as RSA);
464 cert.DSA = (keypair as DSA);
470 public override void Import (byte[] rawData)
472 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
475 [MonoTODO ("missing KeyStorageFlags support")]
476 public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
478 MX.X509Certificate cert = null;
479 if (password == null) {
481 cert = new MX.X509Certificate (rawData);
483 catch (Exception e) {
485 cert = ImportPkcs12 (rawData, null);
488 string msg = Locale.GetText ("Unable to decode certificate.");
489 // inner exception is the original (not second) exception
490 throw new CryptographicException (msg, e);
496 cert = ImportPkcs12 (rawData, password);
499 // it's possible to supply a (unrequired/unusued) password
501 cert = new MX.X509Certificate (rawData);
504 // we do not have to fully re-decode the certificate since X509Certificate does not deal with keys
506 base.Import (cert.RawData, (string) null, keyStorageFlags);
507 _cert = cert; // becuase base call will call Reset!
511 [MonoTODO ("SecureString is incomplete")]
512 public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
514 Import (rawData, (string) null, keyStorageFlags);
517 public override void Import (string fileName)
519 byte[] rawData = File.ReadAllBytes (fileName);
520 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
523 [MonoTODO ("missing KeyStorageFlags support")]
524 public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
526 byte[] rawData = File.ReadAllBytes (fileName);
527 Import (rawData, password, keyStorageFlags);
530 [MonoTODO ("SecureString is incomplete")]
531 public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
533 byte[] rawData = File.ReadAllBytes (fileName);
534 Import (rawData, (string)null, keyStorageFlags);
537 public override void Reset ()
542 _name = String.Empty;
547 signature_algorithm = null;
551 public override string ToString ()
554 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
556 return base.ToString (true);
559 public override string ToString (bool verbose)
562 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
564 // the non-verbose X509Certificate2 == verbose X509Certificate
566 return base.ToString (true);
568 string nl = Environment.NewLine;
569 StringBuilder sb = new StringBuilder ();
570 sb.AppendFormat ("[Version]{0} V{1}{0}{0}", nl, Version);
571 sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, Subject);
572 sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, Issuer);
573 sb.AppendFormat ("[Serial Number]{0} {1}{0}{0}", nl, SerialNumber);
574 sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, NotBefore);
575 sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, NotAfter);
576 sb.AppendFormat ("[Thumbprint]{0} {1}{0}{0}", nl, Thumbprint);
577 sb.AppendFormat ("[Signature Algorithm]{0} {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName,
578 SignatureAlgorithm.Value);
580 AsymmetricAlgorithm key = PublicKey.Key;
581 sb.AppendFormat ("[Public Key]{0} Algorithm: ", nl);
587 sb.Append (key.ToString ());
588 sb.AppendFormat ("{0} Length: {1}{0} Key Blob: ", nl, key.KeySize);
589 AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData);
590 sb.AppendFormat ("{0} Parameters: ", nl);
591 AppendBuffer (sb, PublicKey.EncodedParameters.RawData);
594 return sb.ToString ();
597 private static void AppendBuffer (StringBuilder sb, byte[] buffer)
601 for (int i=0; i < buffer.Length; i++) {
602 sb.Append (buffer [i].ToString ("x2"));
603 if (i < buffer.Length - 1)
608 [MonoTODO ("by default this depends on the incomplete X509Chain")]
609 public bool Verify ()
612 throw new CryptographicException (empty_error);
614 X509Chain chain = X509Chain.Create ();
615 if (!chain.Build (this))
617 // TODO - check chain and other stuff ???
623 private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
625 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")]
626 public static X509ContentType GetCertContentType (byte[] rawData)
628 if ((rawData == null) || (rawData.Length == 0))
629 throw new ArgumentException ("rawData");
631 X509ContentType type = X509ContentType.Unknown;
633 ASN1 data = new ASN1 (rawData);
634 if (data.Tag != 0x30) {
635 string msg = Locale.GetText ("Unable to decode certificate.");
636 throw new CryptographicException (msg);
642 if (data.Count == 3) {
643 switch (data [0].Tag) {
645 // SEQUENCE / SEQUENCE / BITSTRING
646 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03))
647 type = X509ContentType.Cert;
650 // INTEGER / SEQUENCE / SEQUENCE
651 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30))
652 type = X509ContentType.Pkcs12;
653 // note: Pfx == Pkcs12
657 // check for PKCS#7 (count unknown but greater than 0)
658 // SEQUENCE / OID (signedData)
659 if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData))
660 type = X509ContentType.Pkcs7;
662 catch (Exception e) {
663 string msg = Locale.GetText ("Unable to decode certificate.");
664 throw new CryptographicException (msg, e);
670 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")]
671 public static X509ContentType GetCertContentType (string fileName)
673 if (fileName == null)
674 throw new ArgumentNullException ("fileName");
675 if (fileName.Length == 0)
676 throw new ArgumentException ("fileName");
678 byte[] data = File.ReadAllBytes (fileName);
679 return GetCertContentType (data);
682 // internal stuff because X509Certificate2 isn't complete enough
683 // (maybe X509Certificate3 will be better?)
685 internal MX.X509Certificate MonoCertificate {
686 get { return _cert; }
690 // HACK - this ensure the type X509Certificate2 and PrivateKey property exists in the build before
691 // Mono.Security.dll is built. This is required to get working client certificate in SSL/TLS
692 public AsymmetricAlgorithm PrivateKey {