2 // X509Certificate2ImplMono
5 // Sebastien Pouliot <sebastien@xamarin.com>
6 // Martin Baulig <martin.baulig@xamarin.com>
8 // (C) 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Copyright (C) 2004-2006 Novell Inc. (http://www.novell.com)
10 // Copyright (C) 2015-2016 Xamarin, Inc. (http://www.xamarin.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 #if MONO_SECURITY_ALIAS
35 extern alias MonoSecurity;
36 using MonoSecurity::Mono.Security;
37 using MonoSecurity::Mono.Security.Cryptography;
38 using MX = MonoSecurity::Mono.Security.X509;
41 using Mono.Security.Cryptography;
42 using MX = Mono.Security.X509;
47 using System.Collections;
49 namespace System.Security.Cryptography.X509Certificates
51 internal class X509Certificate2ImplMono : X509Certificate2Impl
54 X509ExtensionCollection _extensions;
57 X500DistinguishedName issuer_name;
58 X500DistinguishedName subject_name;
59 Oid signature_algorithm;
61 MX.X509Certificate _cert;
63 static string empty_error = Locale.GetText ("Certificate instance is empty.");
65 public override bool IsValid {
71 public override IntPtr Handle {
72 get { return IntPtr.Zero; }
75 public override IntPtr GetNativeAppleCertificate ()
80 internal X509Certificate2ImplMono (MX.X509Certificate cert)
85 public override X509CertificateImpl Clone ()
87 ThrowIfContextInvalid ();
88 return new X509Certificate2ImplMono (_cert);
91 #region Implemented X509CertificateImpl members
93 public override string GetIssuerName (bool legacyV1Mode)
95 ThrowIfContextInvalid ();
97 return _cert.IssuerName;
99 return MX.X501.ToString (_cert.GetIssuerName (), true, ", ", true);
102 public override string GetSubjectName (bool legacyV1Mode)
104 ThrowIfContextInvalid ();
106 return _cert.SubjectName;
108 return MX.X501.ToString (_cert.GetSubjectName (), true, ", ", true);
111 public override byte[] GetRawCertData ()
113 ThrowIfContextInvalid ();
114 return _cert.RawData;
117 protected override byte[] GetCertHash (bool lazy)
119 ThrowIfContextInvalid ();
120 SHA1 sha = SHA1.Create ();
121 return sha.ComputeHash (_cert.RawData);
124 public override DateTime GetValidFrom ()
126 ThrowIfContextInvalid ();
127 return _cert.ValidFrom;
130 public override DateTime GetValidUntil ()
132 ThrowIfContextInvalid ();
133 return _cert.ValidUntil;
136 public override bool Equals (X509CertificateImpl other, out bool result)
138 // Use default implementation
143 public override string GetKeyAlgorithm ()
145 ThrowIfContextInvalid ();
146 return _cert.KeyAlgorithm;
149 public override byte[] GetKeyAlgorithmParameters ()
151 ThrowIfContextInvalid ();
152 return _cert.KeyAlgorithmParameters;
155 public override byte[] GetPublicKey ()
157 ThrowIfContextInvalid ();
158 return _cert.PublicKey;
161 public override byte[] GetSerialNumber ()
163 ThrowIfContextInvalid ();
164 return _cert.SerialNumber;
167 public override byte[] Export (X509ContentType contentType, byte[] password)
169 ThrowIfContextInvalid ();
171 switch (contentType) {
172 case X509ContentType.Cert:
173 return GetRawCertData ();
174 case X509ContentType.Pfx: // this includes Pkcs12
176 throw new NotSupportedException ();
177 case X509ContentType.SerializedCert:
179 throw new NotSupportedException ();
181 string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
182 throw new CryptographicException (msg);
190 public X509Certificate2ImplMono ()
197 public override bool Archived {
200 throw new CryptographicException (empty_error);
205 throw new CryptographicException (empty_error);
210 public override X509ExtensionCollection Extensions {
213 throw new CryptographicException (empty_error);
214 if (_extensions == null)
215 _extensions = new X509ExtensionCollection (_cert);
220 // FIXME - Could be more efficient
221 public override bool HasPrivateKey {
222 get { return PrivateKey != null; }
225 public override X500DistinguishedName IssuerName {
228 throw new CryptographicException (empty_error);
229 if (issuer_name == null)
230 issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
235 public override AsymmetricAlgorithm PrivateKey {
238 throw new CryptographicException (empty_error);
240 if (_cert.RSA != null) {
241 RSACryptoServiceProvider rcsp = _cert.RSA as RSACryptoServiceProvider;
243 return rcsp.PublicOnly ? null : rcsp;
245 RSAManaged rsam = _cert.RSA as RSAManaged;
247 return rsam.PublicOnly ? null : rsam;
249 _cert.RSA.ExportParameters (true);
251 } else if (_cert.DSA != null) {
252 DSACryptoServiceProvider dcsp = _cert.DSA as DSACryptoServiceProvider;
254 return dcsp.PublicOnly ? null : dcsp;
256 _cert.DSA.ExportParameters (true);
266 throw new CryptographicException (empty_error);
268 // allow NULL so we can "forget" the key associated to the certificate
269 // e.g. in case we want to export it in another format (see bug #396620)
273 } else if (value is RSA)
274 _cert.RSA = (RSA) value;
275 else if (value is DSA)
276 _cert.DSA = (DSA) value;
278 throw new NotSupportedException ();
282 public override PublicKey PublicKey {
285 throw new CryptographicException (empty_error);
287 if (_publicKey == null) {
289 _publicKey = new PublicKey (_cert);
291 catch (Exception e) {
292 string msg = Locale.GetText ("Unable to decode public key.");
293 throw new CryptographicException (msg, e);
300 public override 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 override X500DistinguishedName SubjectName {
314 throw new CryptographicException (empty_error);
316 if (subject_name == null)
317 subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
322 public override int Version {
325 throw new CryptographicException (empty_error);
326 return _cert.Version;
332 [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
333 public override string GetNameInfo (X509NameType nameType, bool forIssuer)
336 case X509NameType.SimpleName:
338 throw new CryptographicException (empty_error);
339 // return CN= or, if missing, the first part of the DN
340 ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
341 ASN1 dn = Find (commonName, sn);
343 return GetValueAsString (dn);
346 ASN1 last_entry = sn [sn.Count - 1];
347 if (last_entry.Count == 0)
349 return GetValueAsString (last_entry [0]);
350 case X509NameType.EmailName:
351 // return the E= part of the DN (if present)
352 ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
354 return GetValueAsString (e);
356 case X509NameType.UpnName:
357 // FIXME - must find/create test case
359 case X509NameType.DnsName:
360 // return the CN= part of the DN (if present)
361 ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
363 return GetValueAsString (cn);
365 case X509NameType.DnsFromAlternativeName:
366 // FIXME - must find/create test case
368 case X509NameType.UrlName:
369 // FIXME - must find/create test case
372 throw new ArgumentException ("nameType");
376 static byte[] commonName = { 0x55, 0x04, 0x03 };
377 static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
379 private ASN1 Find (byte[] oid, ASN1 dn)
385 for (int i = 0; i < dn.Count; i++) {
387 for (int j = 0; j < set.Count; j++) {
392 ASN1 poid = pair [0];
396 if (poid.CompareValue (oid))
403 private string GetValueAsString (ASN1 pair)
408 ASN1 value = pair [1];
409 if ((value.Value == null) || (value.Length == 0))
412 if (value.Tag == 0x1E) {
414 StringBuilder sb = new StringBuilder ();
415 for (int j = 1; j < value.Value.Length; j += 2)
416 sb.Append ((char)value.Value [j]);
417 return sb.ToString ();
419 return Encoding.UTF8.GetString (value.Value);
423 private MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
425 MX.PKCS12 pfx = null;
426 if (string.IsNullOrEmpty (password)) {
428 // Support both unencrypted PKCS#12..
429 pfx = new MX.PKCS12 (rawData, (string)null);
431 // ..and PKCS#12 encrypted with an empty password
432 pfx = new MX.PKCS12 (rawData, string.Empty);
435 pfx = new MX.PKCS12 (rawData, password);
438 if (pfx.Certificates.Count == 0) {
439 // no certificate was found
441 } else if (pfx.Keys.Count == 0) {
442 // no key were found - pick the first certificate
443 return pfx.Certificates [0];
445 // find the certificate that match the first key
446 MX.X509Certificate cert = null;
447 var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
448 string pubkey = keypair.ToXmlString (false);
449 foreach (var c in pfx.Certificates) {
450 if (((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false))) ||
451 ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))) {
457 cert = pfx.Certificates [0]; // no match, pick first certificate without keys
459 cert.RSA = (keypair as RSA);
460 cert.DSA = (keypair as DSA);
466 [MonoTODO ("missing KeyStorageFlags support")]
467 public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
469 MX.X509Certificate cert = null;
470 if (password == null) {
472 cert = new MX.X509Certificate (rawData);
474 catch (Exception e) {
476 cert = ImportPkcs12 (rawData, null);
479 string msg = Locale.GetText ("Unable to decode certificate.");
480 // inner exception is the original (not second) exception
481 throw new CryptographicException (msg, e);
487 cert = ImportPkcs12 (rawData, password);
490 // it's possible to supply a (unrequired/unusued) password
492 cert = new MX.X509Certificate (rawData);
498 [MonoTODO ("X509ContentType.SerializedCert is not supported")]
499 public override byte[] Export (X509ContentType contentType, string password)
502 throw new CryptographicException (empty_error);
504 switch (contentType) {
505 case X509ContentType.Cert:
506 return _cert.RawData;
507 case X509ContentType.Pfx: // this includes Pkcs12
508 return ExportPkcs12 (password);
509 case X509ContentType.SerializedCert:
511 throw new NotSupportedException ();
513 string msg = Locale.GetText ("This certificate format '{0}' cannot be exported.", contentType);
514 throw new CryptographicException (msg);
518 byte[] ExportPkcs12 (string password)
520 var pfx = new MX.PKCS12 ();
522 var attrs = new Hashtable ();
523 var localKeyId = new ArrayList ();
524 localKeyId.Add (new byte[] { 1, 0, 0, 0 });
525 attrs.Add (MX.PKCS9.localKeyId, localKeyId);
527 if (password != null)
528 pfx.Password = password;
529 pfx.AddCertificate (_cert, attrs);
530 var privateKey = PrivateKey;
531 if (privateKey != null)
532 pfx.AddPkcs8ShroudedKeyBag (privateKey, attrs);
533 return pfx.GetBytes ();
539 public override void Reset ()
548 signature_algorithm = null;
551 public override string ToString ()
554 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
556 return ToString (true);
559 public override string ToString (bool verbose)
562 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
564 string nl = Environment.NewLine;
565 StringBuilder sb = new StringBuilder ();
567 // the non-verbose X509Certificate2 == verbose X509Certificate
569 sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, GetSubjectName (false));
570 sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, GetIssuerName (false));
571 sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, GetValidFrom ().ToLocalTime ());
572 sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, GetValidUntil ().ToLocalTime ());
573 sb.AppendFormat ("[Thumbprint]{0} {1}{0}", nl, X509Helper.ToHexString (GetCertHash ()));
575 return sb.ToString ();
578 sb.AppendFormat ("[Version]{0} V{1}{0}{0}", nl, Version);
579 sb.AppendFormat ("[Subject]{0} {1}{0}{0}", nl, GetSubjectName (false));
580 sb.AppendFormat ("[Issuer]{0} {1}{0}{0}", nl, GetIssuerName (false));
581 sb.AppendFormat ("[Serial Number]{0} {1}{0}{0}", nl, GetSerialNumber ());
582 sb.AppendFormat ("[Not Before]{0} {1}{0}{0}", nl, GetValidFrom ().ToLocalTime ());
583 sb.AppendFormat ("[Not After]{0} {1}{0}{0}", nl, GetValidUntil ().ToLocalTime ());
584 sb.AppendFormat ("[Thumbprint]{0} {1}{0}", nl, X509Helper.ToHexString (GetCertHash ()));
585 sb.AppendFormat ("[Signature Algorithm]{0} {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName,
586 SignatureAlgorithm.Value);
588 AsymmetricAlgorithm key = PublicKey.Key;
589 sb.AppendFormat ("[Public Key]{0} Algorithm: ", nl);
595 sb.Append (key.ToString ());
596 sb.AppendFormat ("{0} Length: {1}{0} Key Blob: ", nl, key.KeySize);
597 AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData);
598 sb.AppendFormat ("{0} Parameters: ", nl);
599 AppendBuffer (sb, PublicKey.EncodedParameters.RawData);
602 return sb.ToString ();
605 private static void AppendBuffer (StringBuilder sb, byte[] buffer)
609 for (int i=0; i < buffer.Length; i++) {
610 sb.Append (buffer [i].ToString ("x2"));
611 if (i < buffer.Length - 1)
616 [MonoTODO ("by default this depends on the incomplete X509Chain")]
617 public override bool Verify (X509Certificate2 thisCertificate)
620 throw new CryptographicException (empty_error);
622 X509Chain chain = X509Chain.Create ();
623 if (!chain.Build (thisCertificate))
625 // TODO - check chain and other stuff ???
631 private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
633 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")]
634 public static X509ContentType GetCertContentType (byte[] rawData)
636 if ((rawData == null) || (rawData.Length == 0))
637 throw new ArgumentException ("rawData");
639 X509ContentType type = X509ContentType.Unknown;
641 ASN1 data = new ASN1 (rawData);
642 if (data.Tag != 0x30) {
643 string msg = Locale.GetText ("Unable to decode certificate.");
644 throw new CryptographicException (msg);
650 if (data.Count == 3) {
651 switch (data [0].Tag) {
653 // SEQUENCE / SEQUENCE / BITSTRING
654 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03))
655 type = X509ContentType.Cert;
658 // INTEGER / SEQUENCE / SEQUENCE
659 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30))
660 type = X509ContentType.Pkcs12;
661 // note: Pfx == Pkcs12
665 // check for PKCS#7 (count unknown but greater than 0)
666 // SEQUENCE / OID (signedData)
667 if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData))
668 type = X509ContentType.Pkcs7;
670 catch (Exception e) {
671 string msg = Locale.GetText ("Unable to decode certificate.");
672 throw new CryptographicException (msg, e);
678 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")]
679 public static X509ContentType GetCertContentType (string fileName)
681 if (fileName == null)
682 throw new ArgumentNullException ("fileName");
683 if (fileName.Length == 0)
684 throw new ArgumentException ("fileName");
686 byte[] data = File.ReadAllBytes (fileName);
687 return GetCertContentType (data);
690 // internal stuff because X509Certificate2 isn't complete enough
691 // (maybe X509Certificate3 will be better?)
693 internal MX.X509Certificate MonoCertificate {
694 get { return _cert; }