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 extern alias MonoSecurity;
34 using MonoSecurity::Mono.Security;
35 using MonoSecurity::Mono.Security.Cryptography;
36 using MX = MonoSecurity::Mono.Security.X509;
42 namespace System.Security.Cryptography.X509Certificates {
44 public class X509Certificate2 : X509Certificate {
46 // Used in Mono.Security HttpsClientStream
47 public X509Certificate2 (byte[] rawData)
52 private bool _archived;
53 private X509ExtensionCollection _extensions;
54 private string _name = String.Empty;
55 private string _serial;
56 private PublicKey _publicKey;
57 private X500DistinguishedName issuer_name;
58 private X500DistinguishedName subject_name;
59 private Oid signature_algorithm;
61 private MX.X509Certificate _cert;
63 private static string empty_error = Locale.GetText ("Certificate instance is empty.");
67 public X509Certificate2 ()
72 public X509Certificate2 (byte[] rawData)
74 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
77 public X509Certificate2 (byte[] rawData, string password)
79 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
82 public X509Certificate2 (byte[] rawData, SecureString password)
84 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
87 public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
89 Import (rawData, password, keyStorageFlags);
92 public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
94 Import (rawData, password, keyStorageFlags);
97 public X509Certificate2 (string fileName)
99 Import (fileName, String.Empty, X509KeyStorageFlags.DefaultKeySet);
102 public X509Certificate2 (string fileName, string password)
104 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
107 public X509Certificate2 (string fileName, SecureString password)
109 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
112 public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
114 Import (fileName, password, keyStorageFlags);
117 public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
119 Import (fileName, password, keyStorageFlags);
122 public X509Certificate2 (IntPtr handle) : base (handle)
124 _cert = new MX.X509Certificate (base.GetRawCertData ());
127 public X509Certificate2 (X509Certificate certificate)
130 _cert = new MX.X509Certificate (base.GetRawCertData ());
135 public bool Archived {
138 throw new CryptographicException (empty_error);
143 throw new CryptographicException (empty_error);
148 public X509ExtensionCollection Extensions {
151 throw new CryptographicException (empty_error);
152 if (_extensions == null)
153 _extensions = new X509ExtensionCollection (_cert);
158 public string FriendlyName {
161 throw new CryptographicException (empty_error);
166 throw new CryptographicException (empty_error);
171 // FIXME - Could be more efficient
172 public bool HasPrivateKey {
173 get { return PrivateKey != null; }
176 public X500DistinguishedName IssuerName {
179 throw new CryptographicException (empty_error);
180 if (issuer_name == null)
181 issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
186 public DateTime NotAfter {
189 throw new CryptographicException (empty_error);
190 return _cert.ValidUntil.ToLocalTime ();
194 public DateTime NotBefore {
197 throw new CryptographicException (empty_error);
198 return _cert.ValidFrom.ToLocalTime ();
202 public AsymmetricAlgorithm PrivateKey {
205 throw new CryptographicException (empty_error);
207 if (_cert.RSA != null) {
208 RSACryptoServiceProvider rcsp = _cert.RSA as RSACryptoServiceProvider;
210 return rcsp.PublicOnly ? null : rcsp;
212 RSAManaged rsam = _cert.RSA as RSAManaged;
214 return rsam.PublicOnly ? null : rsam;
216 _cert.RSA.ExportParameters (true);
218 } else if (_cert.DSA != null) {
219 DSACryptoServiceProvider dcsp = _cert.DSA as DSACryptoServiceProvider;
221 return dcsp.PublicOnly ? null : dcsp;
223 _cert.DSA.ExportParameters (true);
233 throw new CryptographicException (empty_error);
235 // allow NULL so we can "forget" the key associated to the certificate
236 // e.g. in case we want to export it in another format (see bug #396620)
240 } else if (value is RSA)
241 _cert.RSA = (RSA) value;
242 else if (value is DSA)
243 _cert.DSA = (DSA) value;
245 throw new NotSupportedException ();
249 public PublicKey PublicKey {
252 throw new CryptographicException (empty_error);
254 if (_publicKey == null) {
256 _publicKey = new PublicKey (_cert);
258 catch (Exception e) {
259 string msg = Locale.GetText ("Unable to decode public key.");
260 throw new CryptographicException (msg, e);
267 public byte[] RawData {
270 throw new CryptographicException (empty_error);
272 return base.GetRawCertData ();
276 public string SerialNumber {
279 throw new CryptographicException (empty_error);
281 if (_serial == null) {
282 StringBuilder sb = new StringBuilder ();
283 byte[] serial = _cert.SerialNumber;
284 for (int i=serial.Length - 1; i >= 0; i--)
285 sb.Append (serial [i].ToString ("X2"));
286 _serial = sb.ToString ();
292 public Oid SignatureAlgorithm {
295 throw new CryptographicException (empty_error);
297 if (signature_algorithm == null)
298 signature_algorithm = new Oid (_cert.SignatureAlgorithm);
299 return signature_algorithm;
303 public X500DistinguishedName SubjectName {
306 throw new CryptographicException (empty_error);
308 if (subject_name == null)
309 subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
314 public string Thumbprint {
315 get { return base.GetCertHashString (); }
321 throw new CryptographicException (empty_error);
322 return _cert.Version;
328 [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
329 public string GetNameInfo (X509NameType nameType, bool forIssuer)
332 case X509NameType.SimpleName:
334 throw new CryptographicException (empty_error);
335 // return CN= or, if missing, the first part of the DN
336 ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
337 ASN1 dn = Find (commonName, sn);
339 return GetValueAsString (dn);
342 ASN1 last_entry = sn [sn.Count - 1];
343 if (last_entry.Count == 0)
345 return GetValueAsString (last_entry [0]);
346 case X509NameType.EmailName:
347 // return the E= part of the DN (if present)
348 ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
350 return GetValueAsString (e);
352 case X509NameType.UpnName:
353 // FIXME - must find/create test case
355 case X509NameType.DnsName:
356 // return the CN= part of the DN (if present)
357 ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
359 return GetValueAsString (cn);
361 case X509NameType.DnsFromAlternativeName:
362 // FIXME - must find/create test case
364 case X509NameType.UrlName:
365 // FIXME - must find/create test case
368 throw new ArgumentException ("nameType");
372 static byte[] commonName = { 0x55, 0x04, 0x03 };
373 static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
375 private ASN1 Find (byte[] oid, ASN1 dn)
381 for (int i = 0; i < dn.Count; i++) {
383 for (int j = 0; j < set.Count; j++) {
388 ASN1 poid = pair [0];
392 if (poid.CompareValue (oid))
399 private string GetValueAsString (ASN1 pair)
404 ASN1 value = pair [1];
405 if ((value.Value == null) || (value.Length == 0))
408 if (value.Tag == 0x1E) {
410 StringBuilder sb = new StringBuilder ();
411 for (int j = 1; j < value.Value.Length; j += 2)
412 sb.Append ((char)value.Value [j]);
413 return sb.ToString ();
415 return Encoding.UTF8.GetString (value.Value);
419 private void ImportPkcs12 (byte[] rawData, string password)
421 MX.PKCS12 pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
422 if (pfx.Certificates.Count > 0) {
423 _cert = pfx.Certificates [0];
427 if (pfx.Keys.Count > 0) {
428 _cert.RSA = (pfx.Keys [0] as RSA);
429 _cert.DSA = (pfx.Keys [0] as DSA);
433 public override void Import (byte[] rawData)
435 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
438 [MonoTODO ("missing KeyStorageFlags support")]
439 public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
441 base.Import (rawData, password, keyStorageFlags);
442 if (password == null) {
444 _cert = new MX.X509Certificate (rawData);
446 catch (Exception e) {
448 ImportPkcs12 (rawData, null);
451 string msg = Locale.GetText ("Unable to decode certificate.");
452 // inner exception is the original (not second) exception
453 throw new CryptographicException (msg, e);
459 ImportPkcs12 (rawData, password);
462 // it's possible to supply a (unrequired/unusued) password
464 _cert = new MX.X509Certificate (rawData);
469 [MonoTODO ("SecureString is incomplete")]
470 public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
472 Import (rawData, (string) null, keyStorageFlags);
475 public override void Import (string fileName)
477 byte[] rawData = Load (fileName);
478 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
481 [MonoTODO ("missing KeyStorageFlags support")]
482 public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
484 byte[] rawData = Load (fileName);
485 Import (rawData, password, keyStorageFlags);
488 [MonoTODO ("SecureString is incomplete")]
489 public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
491 byte[] rawData = Load (fileName);
492 Import (rawData, (string)null, keyStorageFlags);
495 private static byte[] Load (string fileName)
498 using (FileStream fs = File.OpenRead (fileName)) {
499 data = new byte [fs.Length];
500 fs.Read (data, 0, data.Length);
506 public override void Reset ()
511 _name = String.Empty;
516 signature_algorithm = null;
520 public override string ToString ()
523 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
525 return base.ToString (true);
528 public override string ToString (bool verbose)
531 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
533 // the non-verbose X509Certificate2 == verbose X509Certificate
535 return base.ToString (true);
537 string nl = Environment.NewLine;
538 StringBuilder sb = new StringBuilder ();
539 sb.AppendFormat ("[Version]{0} V{1}{0}{0}", nl, Version);
540 sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, Subject);
541 sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, Issuer);
542 sb.AppendFormat ("[Serial Number]{0} {1}{0}{0}", nl, SerialNumber);
543 sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, NotBefore);
544 sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, NotAfter);
545 sb.AppendFormat ("[Thumbprint]{0} {1}{0}{0}", nl, Thumbprint);
546 sb.AppendFormat ("[Signature Algorithm]{0} {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName,
547 SignatureAlgorithm.Value);
549 AsymmetricAlgorithm key = PublicKey.Key;
550 sb.AppendFormat ("[Public Key]{0} Algorithm: ", nl);
556 sb.Append (key.ToString ());
557 sb.AppendFormat ("{0} Length: {1}{0} Key Blob: ", nl, key.KeySize);
558 AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData);
559 sb.AppendFormat ("{0} Parameters: ", nl);
560 AppendBuffer (sb, PublicKey.EncodedParameters.RawData);
563 return sb.ToString ();
566 private static void AppendBuffer (StringBuilder sb, byte[] buffer)
570 for (int i=0; i < buffer.Length; i++) {
571 sb.Append (buffer [i].ToString ("x2"));
572 if (i < buffer.Length - 1)
577 [MonoTODO ("by default this depends on the incomplete X509Chain")]
578 public bool Verify ()
581 throw new CryptographicException (empty_error);
583 X509Chain chain = (X509Chain) CryptoConfig.CreateFromName ("X509Chain");
584 if (!chain.Build (this))
586 // TODO - check chain and other stuff ???
592 private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
594 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")]
595 public static X509ContentType GetCertContentType (byte[] rawData)
597 if ((rawData == null) || (rawData.Length == 0))
598 throw new ArgumentException ("rawData");
600 X509ContentType type = X509ContentType.Unknown;
602 ASN1 data = new ASN1 (rawData);
603 if (data.Tag != 0x30) {
604 string msg = Locale.GetText ("Unable to decode certificate.");
605 throw new CryptographicException (msg);
611 if (data.Count == 3) {
612 switch (data [0].Tag) {
614 // SEQUENCE / SEQUENCE / BITSTRING
615 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03))
616 type = X509ContentType.Cert;
619 // INTEGER / SEQUENCE / SEQUENCE
620 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30))
621 type = X509ContentType.Pkcs12;
622 // note: Pfx == Pkcs12
626 // check for PKCS#7 (count unknown but greater than 0)
627 // SEQUENCE / OID (signedData)
628 if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData))
629 type = X509ContentType.Pkcs7;
631 catch (Exception e) {
632 string msg = Locale.GetText ("Unable to decode certificate.");
633 throw new CryptographicException (msg, e);
639 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")]
640 public static X509ContentType GetCertContentType (string fileName)
642 if (fileName == null)
643 throw new ArgumentNullException ("fileName");
644 if (fileName.Length == 0)
645 throw new ArgumentException ("fileName");
647 byte[] data = Load (fileName);
648 return GetCertContentType (data);
651 // internal stuff because X509Certificate2 isn't complete enough
652 // (maybe X509Certificate3 will be better?)
654 internal MX.X509Certificate MonoCertificate {
655 get { return _cert; }
659 // HACK - this ensure the type X509Certificate2 and PrivateKey property exists in the build before
660 // Mono.Security.dll is built. This is required to get working client certificate in SSL/TLS
661 public AsymmetricAlgorithm PrivateKey {