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.
36 using Mono.Security.Cryptography;
37 using MX = Mono.Security.X509;
40 namespace System.Security.Cryptography.X509Certificates {
42 public class X509Certificate2 : X509Certificate {
44 private bool _archived;
45 private X509ExtensionCollection _extensions;
46 private string _name = String.Empty;
47 private string _serial;
48 private PublicKey _publicKey;
49 private X500DistinguishedName issuer_name;
50 private X500DistinguishedName subject_name;
51 private Oid signature_algorithm;
53 private MX.X509Certificate _cert;
55 private static string empty_error = Locale.GetText ("Certificate instance is empty.");
59 public X509Certificate2 ()
64 public X509Certificate2 (byte[] rawData)
66 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
69 public X509Certificate2 (byte[] rawData, string password)
71 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
74 public X509Certificate2 (byte[] rawData, SecureString password)
76 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
79 public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
81 Import (rawData, password, keyStorageFlags);
84 public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
86 Import (rawData, password, keyStorageFlags);
89 public X509Certificate2 (string fileName)
91 Import (fileName, String.Empty, X509KeyStorageFlags.DefaultKeySet);
94 public X509Certificate2 (string fileName, string password)
96 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
99 public X509Certificate2 (string fileName, SecureString password)
101 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
104 public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
106 Import (fileName, password, keyStorageFlags);
109 public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
111 Import (fileName, password, keyStorageFlags);
114 public X509Certificate2 (IntPtr handle) : base (handle)
116 _cert = new MX.X509Certificate (base.GetRawCertData ());
119 public X509Certificate2 (X509Certificate certificate)
122 _cert = new MX.X509Certificate (base.GetRawCertData ());
127 public bool Archived {
130 throw new CryptographicException (empty_error);
135 throw new CryptographicException (empty_error);
140 public X509ExtensionCollection Extensions {
143 throw new CryptographicException (empty_error);
144 if (_extensions == null)
145 _extensions = new X509ExtensionCollection (_cert);
150 public string FriendlyName {
153 throw new CryptographicException (empty_error);
158 throw new CryptographicException (empty_error);
163 // FIXME - Could be more efficient
164 public bool HasPrivateKey {
165 get { return PrivateKey != null; }
168 public X500DistinguishedName IssuerName {
171 throw new CryptographicException (empty_error);
172 if (issuer_name == null)
173 issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
178 public DateTime NotAfter {
181 throw new CryptographicException (empty_error);
182 return _cert.ValidUntil.ToLocalTime ();
186 public DateTime NotBefore {
189 throw new CryptographicException (empty_error);
190 return _cert.ValidFrom.ToLocalTime ();
194 public AsymmetricAlgorithm PrivateKey {
197 throw new CryptographicException (empty_error);
199 if (_cert.RSA != null) {
200 RSACryptoServiceProvider rcsp = _cert.RSA as RSACryptoServiceProvider;
202 return rcsp.PublicOnly ? null : rcsp;
203 RSAManaged rsam = _cert.RSA as RSAManaged;
205 return rsam.PublicOnly ? null : rsam;
207 _cert.RSA.ExportParameters (true);
209 } else if (_cert.DSA != null) {
210 DSACryptoServiceProvider dcsp = _cert.DSA as DSACryptoServiceProvider;
212 return dcsp.PublicOnly ? null : dcsp;
214 _cert.DSA.ExportParameters (true);
224 throw new CryptographicException (empty_error);
226 // allow NULL so we can "forget" the key associated to the certificate
227 // e.g. in case we want to export it in another format (see bug #396620)
231 } else if (value is RSA)
232 _cert.RSA = (RSA) value;
233 else if (value is DSA)
234 _cert.DSA = (DSA) value;
236 throw new NotSupportedException ();
240 public PublicKey PublicKey {
243 throw new CryptographicException (empty_error);
245 if (_publicKey == null) {
247 _publicKey = new PublicKey (_cert);
249 catch (Exception e) {
250 string msg = Locale.GetText ("Unable to decode public key.");
251 throw new CryptographicException (msg, e);
258 public byte[] RawData {
261 throw new CryptographicException (empty_error);
263 return base.GetRawCertData ();
267 public string SerialNumber {
270 throw new CryptographicException (empty_error);
272 if (_serial == null) {
273 StringBuilder sb = new StringBuilder ();
274 byte[] serial = _cert.SerialNumber;
275 for (int i=serial.Length - 1; i >= 0; i--)
276 sb.Append (serial [i].ToString ("X2"));
277 _serial = sb.ToString ();
283 public Oid SignatureAlgorithm {
286 throw new CryptographicException (empty_error);
288 if (signature_algorithm == null)
289 signature_algorithm = new Oid (_cert.SignatureAlgorithm);
290 return signature_algorithm;
294 public X500DistinguishedName SubjectName {
297 throw new CryptographicException (empty_error);
299 if (subject_name == null)
300 subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
305 public string Thumbprint {
306 get { return base.GetCertHashString (); }
312 throw new CryptographicException (empty_error);
313 return _cert.Version;
319 [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
320 public string GetNameInfo (X509NameType nameType, bool forIssuer)
323 case X509NameType.SimpleName:
325 throw new CryptographicException (empty_error);
326 // return CN= or, if missing, the first part of the DN
327 ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
328 ASN1 dn = Find (commonName, sn);
330 return GetValueAsString (dn);
333 ASN1 last_entry = sn [sn.Count - 1];
334 if (last_entry.Count == 0)
336 return GetValueAsString (last_entry [0]);
337 case X509NameType.EmailName:
338 // return the E= part of the DN (if present)
339 ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
341 return GetValueAsString (e);
343 case X509NameType.UpnName:
344 // FIXME - must find/create test case
346 case X509NameType.DnsName:
347 // return the CN= part of the DN (if present)
348 ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
350 return GetValueAsString (cn);
352 case X509NameType.DnsFromAlternativeName:
353 // FIXME - must find/create test case
355 case X509NameType.UrlName:
356 // FIXME - must find/create test case
359 throw new ArgumentException ("nameType");
363 static byte[] commonName = { 0x55, 0x04, 0x03 };
364 static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
366 private ASN1 Find (byte[] oid, ASN1 dn)
372 for (int i = 0; i < dn.Count; i++) {
374 for (int j = 0; j < set.Count; j++) {
379 ASN1 poid = pair [0];
383 if (poid.CompareValue (oid))
390 private string GetValueAsString (ASN1 pair)
395 ASN1 value = pair [1];
396 if ((value.Value == null) || (value.Length == 0))
399 if (value.Tag == 0x1E) {
401 StringBuilder sb = new StringBuilder ();
402 for (int j = 1; j < value.Value.Length; j += 2)
403 sb.Append ((char)value.Value [j]);
404 return sb.ToString ();
406 return Encoding.UTF8.GetString (value.Value);
410 private void ImportPkcs12 (byte[] rawData, string password)
412 MX.PKCS12 pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
413 if (pfx.Certificates.Count > 0) {
414 _cert = pfx.Certificates [0];
418 if (pfx.Keys.Count > 0) {
419 _cert.RSA = (pfx.Keys [0] as RSA);
420 _cert.DSA = (pfx.Keys [0] as DSA);
424 public override void Import (byte[] rawData)
426 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
429 [MonoTODO ("missing KeyStorageFlags support")]
430 public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
432 base.Import (rawData, password, keyStorageFlags);
433 if (password == null) {
435 _cert = new Mono.Security.X509.X509Certificate (rawData);
437 catch (Exception e) {
439 ImportPkcs12 (rawData, null);
442 string msg = Locale.GetText ("Unable to decode certificate.");
443 // inner exception is the original (not second) exception
444 throw new CryptographicException (msg, e);
450 ImportPkcs12 (rawData, password);
453 // it's possible to supply a (unrequired/unusued) password
455 _cert = new Mono.Security.X509.X509Certificate (rawData);
460 [MonoTODO ("SecureString is incomplete")]
461 public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
463 Import (rawData, (string) null, keyStorageFlags);
466 public override void Import (string fileName)
468 byte[] rawData = Load (fileName);
469 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
472 [MonoTODO ("missing KeyStorageFlags support")]
473 public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
475 byte[] rawData = Load (fileName);
476 Import (rawData, password, keyStorageFlags);
479 [MonoTODO ("SecureString is incomplete")]
480 public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
482 byte[] rawData = Load (fileName);
483 Import (rawData, (string)null, keyStorageFlags);
486 private static byte[] Load (string fileName)
489 using (FileStream fs = File.OpenRead (fileName)) {
490 data = new byte [fs.Length];
491 fs.Read (data, 0, data.Length);
497 public override void Reset ()
502 _name = String.Empty;
507 signature_algorithm = null;
511 public override string ToString ()
514 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
516 return base.ToString (true);
519 public override string ToString (bool verbose)
522 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
524 // the non-verbose X509Certificate2 == verbose X509Certificate
526 return base.ToString (true);
528 string nl = Environment.NewLine;
529 StringBuilder sb = new StringBuilder ();
530 sb.AppendFormat ("[Version]{0} V{1}{0}{0}", nl, Version);
531 sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, Subject);
532 sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, Issuer);
533 sb.AppendFormat ("[Serial Number]{0} {1}{0}{0}", nl, SerialNumber);
534 sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, NotBefore);
535 sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, NotAfter);
536 sb.AppendFormat ("[Thumbprint]{0} {1}{0}{0}", nl, Thumbprint);
537 sb.AppendFormat ("[Signature Algorithm]{0} {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName,
538 SignatureAlgorithm.Value);
540 AsymmetricAlgorithm key = PublicKey.Key;
541 sb.AppendFormat ("[Public Key]{0} Algorithm: ", nl);
547 sb.Append (key.ToString ());
548 sb.AppendFormat ("{0} Length: {1}{0} Key Blob: ", nl, key.KeySize);
549 AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData);
550 sb.AppendFormat ("{0} Parameters: ", nl);
551 AppendBuffer (sb, PublicKey.EncodedParameters.RawData);
554 return sb.ToString ();
557 private static void AppendBuffer (StringBuilder sb, byte[] buffer)
561 for (int i=0; i < buffer.Length; i++) {
562 sb.Append (buffer [i].ToString ("x2"));
563 if (i < buffer.Length - 1)
568 [MonoTODO ("by default this depends on the incomplete X509Chain")]
569 public bool Verify ()
572 throw new CryptographicException (empty_error);
574 X509Chain chain = (X509Chain) CryptoConfig.CreateFromName ("X509Chain");
575 if (!chain.Build (this))
577 // TODO - check chain and other stuff ???
583 private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
585 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")]
586 public static X509ContentType GetCertContentType (byte[] rawData)
588 if ((rawData == null) || (rawData.Length == 0))
589 throw new ArgumentException ("rawData");
591 X509ContentType type = X509ContentType.Unknown;
593 ASN1 data = new ASN1 (rawData);
594 if (data.Tag != 0x30) {
595 string msg = Locale.GetText ("Unable to decode certificate.");
596 throw new CryptographicException (msg);
602 if (data.Count == 3) {
603 switch (data [0].Tag) {
605 // SEQUENCE / SEQUENCE / BITSTRING
606 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03))
607 type = X509ContentType.Cert;
610 // INTEGER / SEQUENCE / SEQUENCE
611 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30))
612 type = X509ContentType.Pkcs12;
613 // note: Pfx == Pkcs12
618 // check for PKCS#7 (count unknown but greater than 0)
619 // SEQUENCE / OID (signedData)
620 if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData))
621 type = X509ContentType.Pkcs7;
623 catch (Exception e) {
624 string msg = Locale.GetText ("Unable to decode certificate.");
625 throw new CryptographicException (msg, e);
631 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")]
632 public static X509ContentType GetCertContentType (string fileName)
634 if (fileName == null)
635 throw new ArgumentNullException ("fileName");
636 if (fileName.Length == 0)
637 throw new ArgumentException ("fileName");
639 byte[] data = Load (fileName);
640 return GetCertContentType (data);
643 // internal stuff because X509Certificate2 isn't complete enough
644 // (maybe X509Certificate3 will be better?)
646 internal MX.X509Certificate MonoCertificate {
647 get { return _cert; }
651 // HACK - this ensure the type X509Certificate2 and PrivateKey property exists in the build before
652 // Mono.Security.dll is built. This is required to get working client certificate in SSL/TLS
653 public AsymmetricAlgorithm PrivateKey {