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.
30 #if NET_2_0 && SECURITY_DEP
35 using Mono.Security.Cryptography;
36 using MX = Mono.Security.X509;
38 namespace System.Security.Cryptography.X509Certificates {
40 public class X509Certificate2 : X509Certificate {
42 private bool _archived;
43 private X509ExtensionCollection _extensions;
44 private string _name = String.Empty;
45 private string _serial;
46 private PublicKey _publicKey;
47 private X500DistinguishedName issuer_name;
48 private X500DistinguishedName subject_name;
49 private Oid signature_algorithm;
51 private MX.X509Certificate _cert;
53 private static string empty_error = Locale.GetText ("Certificate instance is empty.");
57 public X509Certificate2 ()
62 public X509Certificate2 (byte[] rawData)
64 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
67 public X509Certificate2 (byte[] rawData, string password)
69 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
72 public X509Certificate2 (byte[] rawData, SecureString password)
74 Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
77 public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
79 Import (rawData, password, keyStorageFlags);
82 public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
84 Import (rawData, password, keyStorageFlags);
87 public X509Certificate2 (string fileName) : base (fileName)
89 Import (fileName, (string)null, X509KeyStorageFlags.DefaultKeySet);
92 public X509Certificate2 (string fileName, string password)
94 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
97 public X509Certificate2 (string fileName, SecureString password)
99 Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
102 public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
104 Import (fileName, password, keyStorageFlags);
107 public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
109 Import (fileName, password, keyStorageFlags);
112 public X509Certificate2 (IntPtr handle) : base (handle)
114 _cert = new MX.X509Certificate (base.GetRawCertData ());
117 public X509Certificate2 (X509Certificate certificate)
120 _cert = new MX.X509Certificate (base.GetRawCertData ());
125 public bool Archived {
128 throw new CryptographicException (empty_error);
133 throw new CryptographicException (empty_error);
138 public X509ExtensionCollection Extensions {
141 throw new CryptographicException (empty_error);
142 if (_extensions == null)
143 _extensions = new X509ExtensionCollection (_cert);
148 public string FriendlyName {
151 throw new CryptographicException (empty_error);
156 throw new CryptographicException (empty_error);
161 // FIXME - Could be more efficient
162 public bool HasPrivateKey {
163 get { return PrivateKey != null; }
166 public X500DistinguishedName IssuerName {
169 throw new CryptographicException (empty_error);
170 if (issuer_name == null)
171 issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
176 public DateTime NotAfter {
179 throw new CryptographicException (empty_error);
180 return _cert.ValidUntil;
184 public DateTime NotBefore {
187 throw new CryptographicException (empty_error);
188 return _cert.ValidFrom;
192 public AsymmetricAlgorithm PrivateKey {
195 throw new CryptographicException (empty_error);
197 if (_cert.RSA != null) {
198 RSACryptoServiceProvider rcsp = _cert.RSA as RSACryptoServiceProvider;
200 return rcsp.PublicOnly ? null : rcsp;
201 RSAManaged rsam = _cert.RSA as RSAManaged;
203 return rsam.PublicOnly ? null : rsam;
205 _cert.RSA.ExportParameters (true);
207 } else if (_cert.DSA != null) {
208 DSACryptoServiceProvider dcsp = _cert.DSA as DSACryptoServiceProvider;
210 return dcsp.PublicOnly ? null : dcsp;
212 _cert.DSA.ExportParameters (true);
222 throw new CryptographicException (empty_error);
225 _cert.RSA = (RSA) value;
226 else if (value is DSA)
227 _cert.DSA = (DSA) value;
229 throw new NotSupportedException ();
233 public PublicKey PublicKey {
236 throw new CryptographicException (empty_error);
238 if (_publicKey == null) {
240 _publicKey = new PublicKey (_cert);
242 catch (Exception e) {
243 string msg = Locale.GetText ("Unable to decode public key.");
244 throw new CryptographicException (msg, e);
251 public byte[] RawData {
254 throw new CryptographicException (empty_error);
256 return base.GetRawCertData ();
260 public string SerialNumber {
263 throw new CryptographicException (empty_error);
265 if (_serial == null) {
266 StringBuilder sb = new StringBuilder ();
267 byte[] serial = _cert.SerialNumber;
268 for (int i=serial.Length - 1; i >= 0; i--)
269 sb.Append (serial [i].ToString ("X2"));
270 _serial = sb.ToString ();
276 public Oid SignatureAlgorithm {
279 throw new CryptographicException (empty_error);
281 if (signature_algorithm == null)
282 signature_algorithm = new Oid (_cert.SignatureAlgorithm);
283 return signature_algorithm;
287 public X500DistinguishedName SubjectName {
290 throw new CryptographicException (empty_error);
292 if (subject_name == null)
293 subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
298 public string Thumbprint {
299 get { return base.GetCertHashString (); }
305 throw new CryptographicException (empty_error);
306 return _cert.Version;
312 [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
313 public string GetNameInfo (X509NameType nameType, bool forIssuer)
316 case X509NameType.SimpleName:
318 throw new CryptographicException (empty_error);
319 // return CN= or, if missing, the first part of the DN
320 ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
321 ASN1 dn = Find (commonName, sn);
323 return GetValueAsString (dn);
326 ASN1 last_entry = sn [sn.Count - 1];
327 if (last_entry.Count == 0)
329 return GetValueAsString (last_entry [0]);
330 case X509NameType.EmailName:
331 // return the E= part of the DN (if present)
332 ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
334 return GetValueAsString (e);
336 case X509NameType.UpnName:
337 // FIXME - must find/create test case
339 case X509NameType.DnsName:
340 // return the CN= part of the DN (if present)
341 ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
343 return GetValueAsString (cn);
345 case X509NameType.DnsFromAlternativeName:
346 // FIXME - must find/create test case
348 case X509NameType.UrlName:
349 // FIXME - must find/create test case
352 throw new ArgumentException ("nameType");
356 static byte[] commonName = { 0x55, 0x04, 0x03 };
357 static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
359 private ASN1 Find (byte[] oid, ASN1 dn)
365 for (int i = 0; i < dn.Count; i++) {
367 for (int j = 0; j < set.Count; j++) {
372 ASN1 poid = pair [0];
376 if (poid.CompareValue (oid))
383 private string GetValueAsString (ASN1 pair)
388 ASN1 value = pair [1];
389 if ((value.Value == null) || (value.Length == 0))
392 if (value.Tag == 0x1E) {
394 StringBuilder sb = new StringBuilder ();
395 for (int j = 1; j < value.Value.Length; j += 2)
396 sb.Append ((char)value.Value [j]);
397 return sb.ToString ();
399 return Encoding.UTF8.GetString (value.Value);
403 private void ImportPkcs12 (byte[] rawData, string password)
405 MX.PKCS12 pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
406 if (pfx.Certificates.Count > 0) {
407 _cert = pfx.Certificates [0];
411 if (pfx.Keys.Count > 0) {
412 _cert.RSA = (pfx.Keys [0] as RSA);
413 _cert.DSA = (pfx.Keys [0] as DSA);
417 public override void Import (byte[] rawData)
419 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
422 [MonoTODO ("missing KeyStorageFlags support")]
423 public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
425 base.Import (rawData, password, keyStorageFlags);
426 if (password == null) {
428 _cert = new Mono.Security.X509.X509Certificate (rawData);
430 catch (Exception e) {
432 ImportPkcs12 (rawData, null);
435 string msg = Locale.GetText ("Unable to decode certificate.");
436 // inner exception is the original (not second) exception
437 throw new CryptographicException (msg, e);
443 ImportPkcs12 (rawData, password);
446 // it's possible to supply a (unrequired/unusued) password
448 _cert = new Mono.Security.X509.X509Certificate (rawData);
453 [MonoTODO ("SecureString is incomplete")]
454 public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
456 Import (rawData, (string) null, keyStorageFlags);
459 public override void Import (string fileName)
461 byte[] rawData = Load (fileName);
462 Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
465 [MonoTODO ("missing KeyStorageFlags support")]
466 public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
468 byte[] rawData = Load (fileName);
469 Import (rawData, password, keyStorageFlags);
472 [MonoTODO ("SecureString is incomplete")]
473 public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
475 byte[] rawData = Load (fileName);
476 Import (rawData, (string)null, keyStorageFlags);
479 private static byte[] Load (string fileName)
482 using (FileStream fs = File.OpenRead (fileName)) {
483 data = new byte [fs.Length];
484 fs.Read (data, 0, data.Length);
490 public override void Reset ()
495 _name = String.Empty;
500 signature_algorithm = null;
504 public override string ToString ()
507 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
509 return base.ToString (true);
512 public override string ToString (bool verbose)
515 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
517 // the non-verbose X509Certificate2 == verbose X509Certificate
519 return base.ToString (true);
521 string nl = Environment.NewLine;
522 StringBuilder sb = new StringBuilder ();
523 sb.AppendFormat ("[Version]{0} V{1}{0}{0}", nl, Version);
524 sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, Subject);
525 sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, Issuer);
526 sb.AppendFormat ("[Serial Number]{0} {1}{0}{0}", nl, SerialNumber);
527 sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, NotBefore);
528 sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, NotAfter);
529 sb.AppendFormat ("[Thumbprint]{0} {1}{0}{0}", nl, Thumbprint);
530 sb.AppendFormat ("[Signature Algorithm]{0} {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName,
531 SignatureAlgorithm.Value);
533 AsymmetricAlgorithm key = PublicKey.Key;
534 sb.AppendFormat ("[Public Key]{0} Algorithm: ", nl);
540 sb.Append (key.ToString ());
541 sb.AppendFormat ("{0} Length: {1}{0} Key Blob: ", nl, key.KeySize);
542 AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData);
543 sb.AppendFormat ("{0} Parameters: ", nl);
544 AppendBuffer (sb, PublicKey.EncodedParameters.RawData);
547 return sb.ToString ();
550 private static void AppendBuffer (StringBuilder sb, byte[] buffer)
554 for (int i=0; i < buffer.Length; i++) {
555 sb.Append (buffer [i].ToString ("x2"));
556 if (i < buffer.Length - 1)
561 [MonoTODO ("by default this depends on the incomplete X509Chain")]
562 public bool Verify ()
565 throw new CryptographicException (empty_error);
567 X509Chain chain = (X509Chain) CryptoConfig.CreateFromName ("X509Chain");
568 if (!chain.Build (this))
570 // TODO - check chain and other stuff ???
576 private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
578 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")]
579 public static X509ContentType GetCertContentType (byte[] rawData)
581 if ((rawData == null) || (rawData.Length == 0))
582 throw new ArgumentException ("rawData");
584 X509ContentType type = X509ContentType.Unknown;
586 ASN1 data = new ASN1 (rawData);
587 if (data.Tag != 0x30) {
588 string msg = Locale.GetText ("Unable to decode certificate.");
589 throw new CryptographicException (msg);
595 if (data.Count == 3) {
596 switch (data [0].Tag) {
598 // SEQUENCE / SEQUENCE / BITSTRING
599 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03))
600 type = X509ContentType.Cert;
603 // INTEGER / SEQUENCE / SEQUENCE
604 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30))
605 type = X509ContentType.Pkcs12;
606 // note: Pfx == Pkcs12
611 // check for PKCS#7 (count unknown but greater than 0)
612 // SEQUENCE / OID (signedData)
613 if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData))
614 type = X509ContentType.Pkcs7;
616 catch (Exception e) {
617 string msg = Locale.GetText ("Unable to decode certificate.");
618 throw new CryptographicException (msg, e);
624 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")]
625 public static X509ContentType GetCertContentType (string fileName)
627 if (fileName == null)
628 throw new ArgumentNullException ("fileName");
629 if (fileName.Length == 0)
630 throw new ArgumentException ("fileName");
632 byte[] data = Load (fileName);
633 return GetCertContentType (data);
636 // internal stuff because X509Certificate2 isn't complete enough
637 // (maybe X509Certificate3 will be better?)
639 internal MX.X509Certificate MonoCertificate {
640 get { return _cert; }