Inheritance: ICloneable
Esempio n. 1
1
	static void Main(string[] args)
	{
		string host = "localhost";
		if (args.Length > 0)
			host = args[0];

		SslProtocols protocol = SslProtocols.Tls;
		if (args.Length > 1) {
			switch (args [1].ToUpper ()) {
			case "SSL":
				protocol = SslProtocols.Ssl3;
				break;
			}
		}

		X509CertificateCollection certificates = null;
		if (args.Length > 2) {
			string password = null;
			if (args.Length > 3)
				password = args [3];

			p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);

			certificates = new X509CertificateCollection ();
			foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
				certificates.Add(new X509Certificate2(args [2], password));
				break;
			}
		}

		TcpClient client = new TcpClient ();
		client.Connect (host, 4433);
 
 		SslStream ssl = new SslStream (client.GetStream(), false, new RemoteCertificateValidationCallback (CertificateValidation), new LocalCertificateSelectionCallback (ClientCertificateSelection));

		ssl.AuthenticateAsClient (host, certificates, protocol, false); 	
		StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
		sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
		sw.Flush ();

		StreamReader sr = new StreamReader (ssl);
		Console.WriteLine (sr.ReadToEnd ());
	}
        public static X509Certificate2 GenerateCert(string certificateName, RSA key)
        {
            byte[] sn = GenerateSerialNumber();
            string subject = string.Format("CN={0}", certificateName);
            DateTime notBefore = DateTime.Now;
            DateTime notAfter = DateTime.Now.AddYears(20);
            string hashName = "SHA512";

            X509CertificateBuilder cb = new X509CertificateBuilder(3);
            cb.SerialNumber = sn;
            cb.IssuerName = subject;
            cb.NotBefore = notBefore;
            cb.NotAfter = notAfter;
            cb.SubjectName = subject;
            cb.SubjectPublicKey = key;
            cb.Hash = hashName;

            byte[] rawcert = cb.Sign(key);
            PKCS12 p12 = new PKCS12();
            Hashtable attributes = GetAttributes();
            p12.AddCertificate(new Mono.Security.X509.X509Certificate(rawcert), attributes);
            p12.AddPkcs8ShroudedKeyBag(key, attributes);
            rawcert = p12.GetBytes();
            return new X509Certificate2(rawcert, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
        }
Esempio n. 3
0
        //adapted from https://github.com/mono/mono/blob/master/mcs/tools/security/makecert.cs
        public static PKCS12 GeneratePfx(string certificateName, string password)
        {
            byte[] sn = GenerateSerialNumber();
            string subject = string.Format("CN={0}", certificateName);

            DateTime notBefore = DateTime.Now;
            DateTime notAfter = DateTime.Now.AddYears(20);

            var subjectKey = new RSACryptoServiceProvider(2048);
            var hashName = "SHA512";

            var cb = new X509CertificateBuilder(3);
            cb.SerialNumber = sn;
            cb.IssuerName = subject;
            cb.NotBefore = notBefore;
            cb.NotAfter = notAfter;
            cb.SubjectName = subject;
            cb.SubjectPublicKey = subjectKey;
            cb.Hash = hashName;

            var rawcert = cb.Sign(subjectKey);

            var p12 = new PKCS12();
            p12.Password = password;

            var attributes = GetAttributes();

            p12.AddCertificate(new Mono.Security.X509.X509Certificate(rawcert), attributes);
            p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes);

            return p12;
        }
Esempio n. 4
0
        internal static void CreateSelfSignCertificatePfx(
            string fileName,
            string hostname,
            ILogger logger)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            byte[] sn = Guid.NewGuid().ToByteArray();
            string subject = string.Format("CN={0}", hostname);
            string issuer = subject;
            DateTime notBefore = DateTime.Now.AddDays(-2);
            DateTime notAfter = DateTime.Now.AddYears(10);

            RSA issuerKey = RSA.Create();
            issuerKey.FromXmlString(MonoTestRootAgency);
            RSA subjectKey = RSA.Create();

            // serial number MUST be positive
            if ((sn[0] & 0x80) == 0x80)
                sn[0] -= 0x80;

            issuer = subject;
            issuerKey = subjectKey;

            X509CertificateBuilder cb = new X509CertificateBuilder(3);
            cb.SerialNumber = sn;
            cb.IssuerName = issuer;
            cb.NotBefore = notBefore;
            cb.NotAfter = notAfter;
            cb.SubjectName = subject;
            cb.SubjectPublicKey = subjectKey;

            // signature
            cb.Hash = "SHA256";
            byte[] rawcert = cb.Sign(issuerKey);

            PKCS12 p12 = new PKCS12();


            ArrayList list = new ArrayList();
            // we use a fixed array to avoid endianess issues 
            // (in case some tools requires the ID to be 1).
            list.Add(new byte[4] { 1, 0, 0, 0 });
            Hashtable attributes = new Hashtable(1);
            attributes.Add(PKCS9.localKeyId, list);

            p12.AddCertificate(new X509Certificate(rawcert), attributes);

            p12.AddPkcs8ShroudedKeyBag(subjectKey, attributes);
            p12.SaveToFile(fileName);
        }
Esempio n. 5
0
        public static byte[] CreateClientCert(string subjectName, byte[] rootKey, byte[] rootCert)
        {
            if (!subjectName.StartsWith("CN="))
                subjectName = "CN=" + subjectName;

            // Copy the root key since the PrivateKey constructor will blow away the data
            byte[] rootKeyCopy = new byte[rootKey.Length];
            Buffer.BlockCopy(rootKey, 0, rootKeyCopy, 0, rootKey.Length);

            // Load the server's private key and certificate
            PrivateKey pvk = new PrivateKey(rootKeyCopy, null);
            RSA issuerKey = pvk.RSA;
            X509Certificate issuerCert = new X509Certificate(rootCert);

            // Serial number MUST be positive
            byte[] sn = Guid.NewGuid().ToByteArray();
            if ((sn[0] & 0x80) == 0x80)
                sn[0] -= 0x80;

            ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension();
            eku.KeyPurpose.Add("1.3.6.1.5.5.7.3.2"); // Indicates the cert is intended for client auth

            // Generate a client certificate signed by the server root CA
            X509CertificateBuilder cb = new X509CertificateBuilder(3);
            cb.SerialNumber = sn;
            cb.IssuerName = issuerCert.IssuerName;
            cb.NotBefore = DateTime.Now;
            cb.NotAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z
            cb.SubjectName = subjectName;
            cb.SubjectPublicKey = issuerKey;
            cb.Hash = "SHA1";
            cb.Extensions.Add(eku);
            byte[] clientCert = cb.Sign(issuerKey);

            // Generate a PKCS#12 file for the client containing the private key and certificate
            PKCS12 p12 = new PKCS12();
            p12.Password = null;

            ArrayList list = new ArrayList(4);
            // We use a fixed array to avoid endianess issues
            // (in case some tools requires the ID to be 1).
            list.Add(new byte[] { 1, 0, 0, 0 });
            Hashtable attributes = new Hashtable(1);
            attributes.Add(PKCS9.localKeyId, list);

            p12.AddCertificate(new X509Certificate(clientCert), attributes);
            p12.AddCertificate(issuerCert);
            p12.AddPkcs8ShroudedKeyBag(issuerKey, attributes);

            return p12.GetBytes();
        }
Esempio n. 6
0
        public static void CreateRootCert(string issuer, out byte[] rootCert)
        {
            if (!issuer.StartsWith("CN="))
                issuer = "CN=" + issuer;

            // Generate a new issuer key
            RSA issuerKey = (RSA)RSA.Create();

            // Generate a private key
            PrivateKey key = new PrivateKey();
            key.RSA = issuerKey;

            // Serial number MUST be positive
            byte[] sn = Guid.NewGuid().ToByteArray();
            if ((sn[0] & 0x80) == 0x80)
                sn[0] -= 0x80;

            ExtendedKeyUsageExtension eku = new ExtendedKeyUsageExtension();
            eku.KeyPurpose.Add("1.3.6.1.5.5.7.3.1"); // Indicates the cert is intended for server auth
            eku.KeyPurpose.Add("1.3.6.1.5.5.7.3.2"); // Indicates the cert is intended for client auth

            // Generate a self-signed certificate
            X509CertificateBuilder cb = new X509CertificateBuilder(3);
            cb.SerialNumber = sn;
            cb.IssuerName = issuer;
            cb.NotBefore = DateTime.Now;
            cb.NotAfter = new DateTime(643445675990000000); // 12/31/2039 23:59:59Z
            cb.SubjectName = issuer;
            cb.SubjectPublicKey = issuerKey;
            cb.Hash = "SHA1";
            cb.Extensions.Add(eku);

            byte[] serverCert = cb.Sign(issuerKey);

            // Generate a PKCS#12 file containing the certificate and private key
            PKCS12 p12 = new PKCS12();
            p12.Password = null;

            ArrayList list = new ArrayList(4);
            // We use a fixed array to avoid endianess issues
            // (in case some tools requires the ID to be 1).
            list.Add(new byte[] { 1, 0, 0, 0 });
            Hashtable attributes = new Hashtable(1);
            attributes.Add(PKCS9.localKeyId, list);

            p12.AddCertificate(new X509Certificate(serverCert), attributes);
            p12.AddPkcs8ShroudedKeyBag(issuerKey, attributes);

            rootCert = p12.GetBytes();
        }
        private PKCS12 BuildPkcs12(byte[] raw, RSA key)
        {
            PKCS12 p12 = new PKCS12();
            p12.Password = "******";

            ArrayList list = new ArrayList();
            // we use a fixed array to avoid endianess issues (in case some tools requires the ID to be 1).
            list.Add(new byte[4] { 1, 0, 0, 0 });
            Hashtable attributes = new Hashtable(1);
            attributes.Add(PKCS9.localKeyId, list);

            p12.AddCertificate(new X509Certificate(raw), attributes);
            p12.AddPkcs8ShroudedKeyBag(key, attributes);

            return p12;
        }
Esempio n. 8
0
	static void Main(string[] args)
	{
		string host = "localhost";
		if (args.Length > 0)
			host = args[0];

		SecurityProtocolType protocol = SecurityProtocolType.Tls;
		if (args.Length > 1) {
			switch (args [1].ToUpper ()) {
			case "SSL":
				protocol = SecurityProtocolType.Ssl3;
				break;
			}
		}

		X509CertificateCollection certificates = null;
		if (args.Length > 2) {
			string password = null;
			if (args.Length > 3)
				password = args [3];

			p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password);

			certificates = new X509CertificateCollection ();
			foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) {
				certificates.Add(new X509Certificate(cert.RawData));
			}
		}

		TcpClient client = new TcpClient ();
		client.Connect (host, 4433);
 
 		SslClientStream ssl = new SslClientStream (client.GetStream(), host, false, protocol, certificates);
 		ssl.ServerCertValidationDelegate += new CertificateValidationCallback (CertificateValidation);
 		ssl.ClientCertSelectionDelegate += new CertificateSelectionCallback (ClientCertificateSelection);
 		ssl.PrivateKeyCertSelectionDelegate += new PrivateKeySelectionCallback (PrivateKeySelection);
	
		StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII);
		sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine);
		sw.Flush ();

		StreamReader sr = new StreamReader (ssl);
		Console.WriteLine (sr.ReadToEnd ());
	}
Esempio n. 9
0
        byte[] ExportPkcs12(string password)
        {
            var pfx = new MX.PKCS12();

            try {
                if (password != null)
                {
                    pfx.Password = password;
                }
                pfx.AddCertificate(_cert);
                var privateKey = PrivateKey;
                if (privateKey != null)
                {
                    pfx.AddPkcs8ShroudedKeyBag(privateKey);
                }
                return(pfx.GetBytes());
            } finally {
                pfx.Password = null;
            }
        }
Esempio n. 10
0
		public object Clone ()
		{
			PKCS12 clone = null;
			if (_password != null) {
				clone = new PKCS12 (GetBytes (), Encoding.BigEndianUnicode.GetString (_password));
			} else {
				clone = new PKCS12 (GetBytes ());
			}
			clone.IterationCount = this.IterationCount;

			return clone;
		}
Esempio n. 11
0
		public void GetAttributes_Test1 ()
		{
			PKCS12 p12 = new PKCS12 ();

			IDictionary attrs = new Hashtable ();
			ArrayList attrValues = new ArrayList ();
			attrValues.Add (Encoding.BigEndianUnicode.GetBytes ("Friendly name"));
			attrs.Add (PKCS9.friendlyName, attrValues);

			AsymmetricAlgorithm aa = RSA.Create ();
			p12.AddKeyBag (aa, attrs);

			AssertEquals ("GA1.1", p12.Keys.Count, 1);

			IDictionary pattrs = p12.GetAttributes (aa);

			Assert ("GA1.2", pattrs.Contains (PKCS9.friendlyName));
		}
Esempio n. 12
0
		public void GetAttributes_Test2 ()
		{
			PKCS12 p12 = new PKCS12 ();
			X509Certificate x509 = new X509Certificate (cert);

			IDictionary attrs = new Hashtable ();
			ArrayList attrValues = new ArrayList ();
			attrValues.Add (Encoding.BigEndianUnicode.GetBytes ("Friendly name"));
			attrs.Add (PKCS9.friendlyName, attrValues);

			p12.AddCertificate (x509, attrs);

			AssertEquals ("GA2.1", p12.Certificates.Count, 1);

			IDictionary pattrs = p12.GetAttributes (x509);

			Assert ("GA2.2", pattrs.Contains (PKCS9.friendlyName));
		}
Esempio n. 13
0
		public void GetAsymmetricAlgorithm_Test ()
		{
			PKCS12 p12 = new PKCS12 ();

			IDictionary attrs = new Hashtable ();
			ArrayList attrValues = new ArrayList ();
			attrValues.Add (Encoding.BigEndianUnicode.GetBytes ("Friendly name"));
			attrs.Add (PKCS9.friendlyName, attrValues);

			p12.AddKeyBag (RSA.Create (), attrs);

			AssertEquals ("GA.1", p12.Keys.Count, 1);

			AsymmetricAlgorithm aa = p12.GetAsymmetricAlgorithm (attrs);

			AssertNotNull ("GA.2", aa);
		}
Esempio n. 14
0
		public void GetCertificate_Test ()
		{
			PKCS12 p12 = new PKCS12 ();
			X509Certificate x509 = new X509Certificate (cert);

			IDictionary attrs = new Hashtable ();
			ArrayList attrValues = new ArrayList ();
			attrValues.Add (Encoding.BigEndianUnicode.GetBytes ("Friendly name"));
			attrs.Add (PKCS9.friendlyName, attrValues);

			p12.AddCertificate (x509, attrs);

			AssertEquals ("GC.1", p12.Certificates.Count, 1);

			X509Certificate xc = p12.GetCertificate (attrs);

			AssertNotNull ("GC.2", xc);
			Assert ("GC.3", Compare (x509.RawData, xc.RawData));
		}
Esempio n. 15
0
		public void Farscape_Strong_Path () 
		{
			// exported from MS certificate manager with strong encryption
			// and including the certificate path
			PKCS12 p12 = new PKCS12 (farscape_strong_path_pfx, "farscape");
			RSA rsa = (RSA) p12.Keys [0];
			X509Certificate x509 = p12.Certificates [0];
			AssertEquals (rsa.ToXmlString (false), x509.RSA.ToXmlString (false));
		}
Esempio n. 16
0
		public void RemoveKeyBag_Test ()
		{
			PKCS12 p12 = new PKCS12 ();

			p12.AddKeyBag (RSA.Create ());

			AssertEquals ("RK.1", p12.Keys.Count, 1);

			p12.RemoveKeyBag (RSA.Create ());

			AssertEquals ("RK.2", p12.Keys.Count, 0);
		}
Esempio n. 17
0
		public void RemovePkcs8ShroudedKeyBag_Test ()
		{
			PKCS12 p12 = new PKCS12 ();

			p12.AddPkcs8ShroudedKeyBag (RSA.Create ());

			AssertEquals ("RP.1", p12.Keys.Count, 1);

			p12.RemovePkcs8ShroudedKeyBag (RSA.Create ());

			AssertEquals ("RP.2", p12.Keys.Count, 0);
		}
Esempio n. 18
0
		public void AddKeyBag_Test1 ()
		{
			PKCS12 p12 = new PKCS12 ();

			p12.AddKeyBag (RSA.Create ());

			AssertEquals ("AK1", p12.Keys.Count, 1);
		}
        private static byte[] CreateRawCert(string certName, string password)
        {
            if (String.IsNullOrEmpty(certName)) {
                Log.To.Listener.E(Tag, "An empty certName was received in CreateRawCert, throwing...");
                throw new ArgumentException("Must contain a non-empty name", "certName");
            }

            if (String.IsNullOrEmpty(password)) {
                Log.To.Listener.E(Tag, "An empty password was received in CreateRawCert, throwing...");
                throw new ArgumentException("Must contain a non-empty password", "password");
            }

            byte[] sn = GenerateSerialNumber();
            string subject = string.Format("CN={0}", certName);
            DateTime notBefore = DateTime.Now;
            DateTime notAfter = DateTime.Now.AddYears(20);
            string hashName = "SHA512";
            var key = new RSACryptoServiceProvider(2048);

            X509CertificateBuilder cb = new X509CertificateBuilder(3);
            cb.SerialNumber = sn;
            cb.IssuerName = subject;
            cb.NotBefore = notBefore;
            cb.NotAfter = notAfter;
            cb.SubjectName = subject;
            cb.SubjectPublicKey = key;
            cb.Hash = hashName;

            Log.To.Listener.I(Tag, "Generating X509 certificate, this is expensive...");
            var sw = System.Diagnostics.Stopwatch.StartNew();
            byte[] rawcert = cb.Sign(key);
            sw.Stop();
            Log.To.Listener.I(Tag, "Finished generating X509 certificate; took {0} sec", sw.ElapsedMilliseconds / 1000.0);
            PKCS12 p12 = new PKCS12();
            if (!String.IsNullOrEmpty(password)) {
                p12.Password = password;
            }
            Hashtable attributes = GetAttributes();
            p12.AddCertificate(new Mono.Security.X509.X509Certificate(rawcert), attributes);
            p12.AddPkcs8ShroudedKeyBag(key, attributes);

            return p12.GetBytes();
        }
Esempio n. 20
0
		public void Farscape_NoPassword_Explicit () 
		{
			// exported from MS certificate manager WITHOUT password
			PKCS12 p12 = new PKCS12 (farscape_nopwd_pfx, (string)null);
			RSA rsa = (RSA) p12.Keys [0];
			X509Certificate x509 = p12.Certificates [0];
			AssertEquals (rsa.ToXmlString (false), x509.RSA.ToXmlString (false));
		}
		public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
		{
			base.Import (rawData, password, keyStorageFlags);
			if (password == null) {
				_cert = new Mono.Security.X509.X509Certificate (rawData);
				// TODO - PKCS12 without password
			} else {
				// try PKCS#12
				MX.PKCS12 pfx = new MX.PKCS12 (rawData, password);
				if (pfx.Certificates.Count > 0) {
					_cert = pfx.Certificates [0];
				} else {
					_cert = null;
				}
				if (pfx.Keys.Count > 0) {
					_cert.RSA = (pfx.Keys [0] as RSA);
					_cert.DSA = (pfx.Keys [0] as DSA);
				}
			}
		}
Esempio n. 22
0
		public void Clone_Test ()
		{
			PKCS12 p12 = new PKCS12 (farscape_nopwd_pfx);
			PKCS12 cp12 = (PKCS12) p12.Clone ();

			Assert ("C1", ! (p12 == cp12));
		}
Esempio n. 23
0
		public void BadFarscape () 
		{
			byte[] p12data = (byte[]) farscape_pfx.Clone ();
			p12data [38] = 0xFF;
			PKCS12 p12 = new PKCS12 (p12data, "farscape");
		}
Esempio n. 24
0
        private static PKCS12 UnlockPfx(byte[] data)
        {
            PKCS12 pfx;

            try
            {
                pfx = new PKCS12(data);
            }
            catch
            {
                try
                {
                    pfx = new PKCS12(data, string.Empty);
                }
                catch
                {
                    try
                    {
                        if (_passphrase == null)
                        {
                            Console.Write("Please enter the passphrase for the KeyFile (will be visible when typed): ");
                            _passphrase = Console.ReadLine();
                        }
                        pfx = new PKCS12(data, _passphrase);
                    }
                    catch
                    {
                        _passphrase = null;
                        throw;
                    }
                }
            }
            return pfx;
        }
Esempio n. 25
0
		public void AddKeyBag_Test2 ()
		{
			PKCS12 p12 = new PKCS12 ();

			IDictionary attrs = new Hashtable ();
			ArrayList attrValues = new ArrayList ();
			attrValues.Add (Encoding.BigEndianUnicode.GetBytes ("Friendly name"));
			attrs.Add (PKCS9.friendlyName, attrValues);

			p12.AddKeyBag (RSA.Create (), attrs);

			AssertEquals ("AK2", p12.Keys.Count, 1);
		}
Esempio n. 26
0
		public void AddCertificate_Test1 ()
		{
			PKCS12 p12 = new PKCS12 ();
			X509Certificate x509 = new X509Certificate (cert);
			p12.AddCertificate (x509);

			AssertEquals ("AC1.1", p12.Certificates.Count, 1);
			Assert ("AC1.2", Compare (p12.Certificates [0].RawData, cert));
		}
Esempio n. 27
0
		public void Farscape_Weak () 
		{
			// exported from MS certificate manager WITHOUT strong encryption
			PKCS12 p12 = new PKCS12 (farscape_pfx, "farscape");
			RSA rsa = (RSA) p12.Keys [0];
			X509Certificate x509 = p12.Certificates [0];
			AssertEquals (rsa.ToXmlString (false), x509.RSA.ToXmlString (false));
		}
Esempio n. 28
0
		public virtual void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
		{
			Reset ();
			if (password == null) {
				try {
					x509 = new Mono.Security.X509.X509Certificate (rawData);
				}
				catch (Exception e) {
					try {
						PKCS12 pfx = new PKCS12 (rawData);
						if (pfx.Certificates.Count > 0)
							x509 = pfx.Certificates [0];
						else
							x509 = null;
					}
					catch {
						string msg = Locale.GetText ("Unable to decode certificate.");
						// inner exception is the original (not second) exception
						throw new CryptographicException (msg, e);
					}
				}
			} else {
				// try PKCS#12
				try {
					PKCS12 pfx = new PKCS12 (rawData, password);
					if (pfx.Certificates.Count > 0) {
						x509 = pfx.Certificates [0];
					} else {
						x509 = null;
					}
				}
				catch {
					// it's possible to supply a (unrequired/unusued) password
					// fix bug #79028
					x509 = new Mono.Security.X509.X509Certificate (rawData);
				}
			}
		}
Esempio n. 29
0
		public void RemoveCertificate_Test1 ()
		{
			PKCS12 p12 = new PKCS12 ();
			X509Certificate x509 = new X509Certificate (cert);
			p12.AddCertificate (x509);

			AssertEquals ("RC1.1", p12.Certificates.Count, 1);

			p12.RemoveCertificate (x509);

			AssertEquals ("RC1.2", p12.Certificates.Count, 0);
		}
Esempio n. 30
0
		private MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
		{
			MX.PKCS12 pfx = null;
			if (string.IsNullOrEmpty (password)) {
				try {
					// Support both unencrypted PKCS#12..
					pfx = new MX.PKCS12 (rawData, (string)null);
				} catch {
					// ..and PKCS#12 encrypted with an empty password
					pfx = new MX.PKCS12 (rawData, string.Empty);
				}
			} else {
				pfx = new MX.PKCS12 (rawData, password);
			}

			if (pfx.Certificates.Count == 0) {
				// no certificate was found
				return null;
			} else if (pfx.Keys.Count == 0) {
				// no key were found - pick the first certificate
				return pfx.Certificates [0];
			} else {
				// find the certificate that match the first key
				MX.X509Certificate cert = null;
				var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
				string pubkey = keypair.ToXmlString (false);
				foreach (var c in pfx.Certificates) {
					if (((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false))) ||
						((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))) {
						cert = c;
						break;
					}
				}
				if (cert == null) {
					cert = pfx.Certificates [0]; // no match, pick first certificate without keys
				} else {
					cert.RSA = (keypair as RSA);
					cert.DSA = (keypair as DSA);
				}
				return cert;
			}
		}
Esempio n. 31
0
		public void RemoveCertificate_Test2 ()
		{
			PKCS12 p12 = new PKCS12 ();
			X509Certificate x509 = new X509Certificate (cert);

			IDictionary attrs = new Hashtable ();
			ArrayList attrValues = new ArrayList ();
			attrValues.Add (Encoding.BigEndianUnicode.GetBytes ("Friendly name"));
			attrs.Add (PKCS9.friendlyName, attrValues);

			p12.AddCertificate (x509, attrs);

			AssertEquals ("RC2.1", p12.Certificates.Count, 1);

			p12.RemoveCertificate (x509, attrs);

			AssertEquals ("RC2.2", p12.Certificates.Count, 0);
		}