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 SECURITY_DEP || MOONLIGHT
34 using Mono.Security.Cryptography;
35 using MX = Mono.Security.X509;
38 namespace System.Security.Cryptography.X509Certificates {
40 public class X509Certificate2 : X509Certificate {
41 #if !SECURITY_DEP && !MOONLIGHT
42 // Used in Mono.Security HttpsClientStream
43 public X509Certificate2 (byte[] rawData)
47 #if SECURITY_DEP || MOONLIGHT
48 private bool _archived;
49 private X509ExtensionCollection _extensions;
50 private string _name = String.Empty;
51 private string _serial;
52 private PublicKey _publicKey;
53 private X500DistinguishedName issuer_name;
54 private X500DistinguishedName subject_name;
55 private Oid signature_algorithm;
57 private MX.X509Certificate _cert;
59 private static string empty_error = Locale.GetText ("Certificate instance is empty.");
63 public X509Certificate2 ()
68 public X509Certificate2 (byte[] rawData)
70 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
73 public X509Certificate2 (byte[] rawData, string password)
75 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
78 public X509Certificate2 (byte[] rawData, SecureString password)
80 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
83 public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
85 Import (rawData, password, keyStorageFlags);
88 public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
90 Import (rawData, password, keyStorageFlags);
93 public X509Certificate2 (string fileName)
95 Import (fileName, String.Empty, X509KeyStorageFlags.DefaultKeySet);
98 public X509Certificate2 (string fileName, string password)
100 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
103 public X509Certificate2 (string fileName, SecureString password)
105 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
108 public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
110 Import (fileName, password, keyStorageFlags);
113 public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
115 Import (fileName, password, keyStorageFlags);
118 public X509Certificate2 (IntPtr handle) : base (handle)
120 _cert = new MX.X509Certificate (base.GetRawCertData ());
123 public X509Certificate2 (X509Certificate certificate)
126 _cert = new MX.X509Certificate (base.GetRawCertData ());
131 public bool Archived {
134 throw new CryptographicException (empty_error);
139 throw new CryptographicException (empty_error);
144 public X509ExtensionCollection Extensions {
147 throw new CryptographicException (empty_error);
148 if (_extensions == null)
149 _extensions = new X509ExtensionCollection (_cert);
154 public string FriendlyName {
157 throw new CryptographicException (empty_error);
162 throw new CryptographicException (empty_error);
167 // FIXME - Could be more efficient
168 public bool HasPrivateKey {
169 get { return PrivateKey != null; }
172 public X500DistinguishedName IssuerName {
175 throw new CryptographicException (empty_error);
176 if (issuer_name == null)
177 issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
182 public DateTime NotAfter {
185 throw new CryptographicException (empty_error);
186 return _cert.ValidUntil.ToLocalTime ();
190 public DateTime NotBefore {
193 throw new CryptographicException (empty_error);
194 return _cert.ValidFrom.ToLocalTime ();
198 public AsymmetricAlgorithm PrivateKey {
201 throw new CryptographicException (empty_error);
203 if (_cert.RSA != null) {
205 RSACryptoServiceProvider rcsp = _cert.RSA as RSACryptoServiceProvider;
207 return rcsp.PublicOnly ? null : rcsp;
209 RSAManaged rsam = _cert.RSA as RSAManaged;
211 return rsam.PublicOnly ? null : rsam;
213 _cert.RSA.ExportParameters (true);
215 } else if (_cert.DSA != null) {
217 DSACryptoServiceProvider dcsp = _cert.DSA as DSACryptoServiceProvider;
219 return dcsp.PublicOnly ? null : dcsp;
221 _cert.DSA.ExportParameters (true);
231 throw new CryptographicException (empty_error);
233 // allow NULL so we can "forget" the key associated to the certificate
234 // e.g. in case we want to export it in another format (see bug #396620)
238 } else if (value is RSA)
239 _cert.RSA = (RSA) value;
240 else if (value is DSA)
241 _cert.DSA = (DSA) value;
243 throw new NotSupportedException ();
247 public PublicKey PublicKey {
250 throw new CryptographicException (empty_error);
252 if (_publicKey == null) {
254 _publicKey = new PublicKey (_cert);
256 catch (Exception e) {
257 string msg = Locale.GetText ("Unable to decode public key.");
258 throw new CryptographicException (msg, e);
265 public byte[] RawData {
268 throw new CryptographicException (empty_error);
270 return base.GetRawCertData ();
274 public string SerialNumber {
277 throw new CryptographicException (empty_error);
279 if (_serial == null) {
280 StringBuilder sb = new StringBuilder ();
281 byte[] serial = _cert.SerialNumber;
282 for (int i=serial.Length - 1; i >= 0; i--)
283 sb.Append (serial [i].ToString ("X2"));
284 _serial = sb.ToString ();
290 public Oid SignatureAlgorithm {
293 throw new CryptographicException (empty_error);
295 if (signature_algorithm == null)
296 signature_algorithm = new Oid (_cert.SignatureAlgorithm);
297 return signature_algorithm;
301 public X500DistinguishedName SubjectName {
304 throw new CryptographicException (empty_error);
306 if (subject_name == null)
307 subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
312 public string Thumbprint {
313 get { return base.GetCertHashString (); }
319 throw new CryptographicException (empty_error);
320 return _cert.Version;
326 [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
327 public string GetNameInfo (X509NameType nameType, bool forIssuer)
330 case X509NameType.SimpleName:
332 throw new CryptographicException (empty_error);
333 // return CN= or, if missing, the first part of the DN
334 ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
335 ASN1 dn = Find (commonName, sn);
337 return GetValueAsString (dn);
340 ASN1 last_entry = sn [sn.Count - 1];
341 if (last_entry.Count == 0)
343 return GetValueAsString (last_entry [0]);
344 case X509NameType.EmailName:
345 // return the E= part of the DN (if present)
346 ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
348 return GetValueAsString (e);
350 case X509NameType.UpnName:
351 // FIXME - must find/create test case
353 case X509NameType.DnsName:
354 // return the CN= part of the DN (if present)
355 ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
357 return GetValueAsString (cn);
359 case X509NameType.DnsFromAlternativeName:
360 // FIXME - must find/create test case
362 case X509NameType.UrlName:
363 // FIXME - must find/create test case
366 throw new ArgumentException ("nameType");
370 static byte[] commonName = { 0x55, 0x04, 0x03 };
371 static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
373 private ASN1 Find (byte[] oid, ASN1 dn)
379 for (int i = 0; i < dn.Count; i++) {
381 for (int j = 0; j < set.Count; j++) {
386 ASN1 poid = pair [0];
390 if (poid.CompareValue (oid))
397 private string GetValueAsString (ASN1 pair)
402 ASN1 value = pair [1];
403 if ((value.Value == null) || (value.Length == 0))
406 if (value.Tag == 0x1E) {
408 StringBuilder sb = new StringBuilder ();
409 for (int j = 1; j < value.Value.Length; j += 2)
410 sb.Append ((char)value.Value [j]);
411 return sb.ToString ();
413 return Encoding.UTF8.GetString (value.Value);
417 private void ImportPkcs12 (byte[] rawData, string password)
419 MX.PKCS12 pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
420 if (pfx.Certificates.Count > 0) {
421 _cert = pfx.Certificates [0];
425 if (pfx.Keys.Count > 0) {
426 _cert.RSA = (pfx.Keys [0] as RSA);
427 _cert.DSA = (pfx.Keys [0] as DSA);
431 public override void Import (byte[] rawData)
433 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
436 [MonoTODO ("missing KeyStorageFlags support")]
437 public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
439 base.Import (rawData, password, keyStorageFlags);
440 if (password == null) {
442 _cert = new Mono.Security.X509.X509Certificate (rawData);
444 catch (Exception e) {
446 ImportPkcs12 (rawData, null);
449 string msg = Locale.GetText ("Unable to decode certificate.");
450 // inner exception is the original (not second) exception
451 throw new CryptographicException (msg, e);
457 ImportPkcs12 (rawData, password);
460 // it's possible to supply a (unrequired/unusued) password
462 _cert = new Mono.Security.X509.X509Certificate (rawData);
468 [MonoTODO ("SecureString is incomplete")]
469 public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
471 Import (rawData, (string) null, keyStorageFlags);
474 public override void Import (string fileName)
476 byte[] rawData = Load (fileName);
477 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
480 [MonoTODO ("missing KeyStorageFlags support")]
481 public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
483 byte[] rawData = Load (fileName);
484 Import (rawData, password, keyStorageFlags);
487 [MonoTODO ("SecureString is incomplete")]
488 public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
490 byte[] rawData = Load (fileName);
491 Import (rawData, (string)null, keyStorageFlags);
494 private static byte[] Load (string fileName)
497 using (FileStream fs = File.OpenRead (fileName)) {
498 data = new byte [fs.Length];
499 fs.Read (data, 0, data.Length);
505 public override void Reset ()
510 _name = String.Empty;
515 signature_algorithm = null;
519 public override string ToString ()
522 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
524 return base.ToString (true);
527 public override string ToString (bool verbose)
530 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
532 // the non-verbose X509Certificate2 == verbose X509Certificate
534 return base.ToString (true);
536 string nl = Environment.NewLine;
537 StringBuilder sb = new StringBuilder ();
538 sb.AppendFormat ("[Version]{0} V{1}{0}{0}", nl, Version);
539 sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, Subject);
540 sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, Issuer);
541 sb.AppendFormat ("[Serial Number]{0} {1}{0}{0}", nl, SerialNumber);
542 sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, NotBefore);
543 sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, NotAfter);
544 sb.AppendFormat ("[Thumbprint]{0} {1}{0}{0}", nl, Thumbprint);
545 sb.AppendFormat ("[Signature Algorithm]{0} {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName,
546 SignatureAlgorithm.Value);
548 AsymmetricAlgorithm key = PublicKey.Key;
549 sb.AppendFormat ("[Public Key]{0} Algorithm: ", nl);
555 sb.Append (key.ToString ());
556 sb.AppendFormat ("{0} Length: {1}{0} Key Blob: ", nl, key.KeySize);
557 AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData);
558 sb.AppendFormat ("{0} Parameters: ", nl);
559 AppendBuffer (sb, PublicKey.EncodedParameters.RawData);
562 return sb.ToString ();
565 private static void AppendBuffer (StringBuilder sb, byte[] buffer)
569 for (int i=0; i < buffer.Length; i++) {
570 sb.Append (buffer [i].ToString ("x2"));
571 if (i < buffer.Length - 1)
576 [MonoTODO ("by default this depends on the incomplete X509Chain")]
577 public bool Verify ()
580 throw new CryptographicException (empty_error);
582 X509Chain chain = (X509Chain) CryptoConfig.CreateFromName ("X509Chain");
583 if (!chain.Build (this))
585 // TODO - check chain and other stuff ???
591 private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
593 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")]
594 public static X509ContentType GetCertContentType (byte[] rawData)
596 if ((rawData == null) || (rawData.Length == 0))
597 throw new ArgumentException ("rawData");
599 X509ContentType type = X509ContentType.Unknown;
601 ASN1 data = new ASN1 (rawData);
602 if (data.Tag != 0x30) {
603 string msg = Locale.GetText ("Unable to decode certificate.");
604 throw new CryptographicException (msg);
610 if (data.Count == 3) {
611 switch (data [0].Tag) {
613 // SEQUENCE / SEQUENCE / BITSTRING
614 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03))
615 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
628 // check for PKCS#7 (count unknown but greater than 0)
629 // SEQUENCE / OID (signedData)
630 if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData))
631 type = X509ContentType.Pkcs7;
634 catch (Exception e) {
635 string msg = Locale.GetText ("Unable to decode certificate.");
636 throw new CryptographicException (msg, e);
642 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")]
643 public static X509ContentType GetCertContentType (string fileName)
645 if (fileName == null)
646 throw new ArgumentNullException ("fileName");
647 if (fileName.Length == 0)
648 throw new ArgumentException ("fileName");
650 byte[] data = Load (fileName);
651 return GetCertContentType (data);
654 // internal stuff because X509Certificate2 isn't complete enough
655 // (maybe X509Certificate3 will be better?)
657 internal MX.X509Certificate MonoCertificate {
658 get { return _cert; }
662 // HACK - this ensure the type X509Certificate2 and PrivateKey property exists in the build before
663 // Mono.Security.dll is built. This is required to get working client certificate in SSL/TLS
664 public AsymmetricAlgorithm PrivateKey {