public bool IsContactCertificateInStore(string strContactID)
        {
            bool bRetVal = false;

            X509CertificateStore certStore = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);

            if (certStore == null)
            {
                throw new Exception("Error opening Local Machine Store");
            }

            if (certStore.OpenRead())
            {
                X509CertificateCollection certColl = certStore.FindCertificateBySubjectName(strContactID);
                if (certColl.Count == 0)
                {
                    bRetVal = false;
                }
                else
                {
                    bRetVal = true;
                }
            }

            // Close the certificate store
            certStore.Close();

            return(bRetVal);
        }
        public void TestImportExportPkcs12()
        {
            var store = new X509CertificateStore();

            store.Import(GetTestDataPath("smime.p12"), "no.secret");
            var certificate = store.Certificates.FirstOrDefault();
            var count       = store.Certificates.Count();

            Assert.AreEqual(1, count, "Unexpected number of certificates imported.");
            Assert.IsNotNull(store.GetPrivateKey(certificate), "Failed to get private key.");

            foreach (var authority in CertificateAuthorities)
            {
                store.Import(GetTestDataPath(authority));
            }

            store.Export("exported.p12", "no.secret");

            var imported = new X509CertificateStore();

            imported.Import("exported.p12", "no.secret");

            count = imported.Certificates.Count();

            Assert.AreEqual(store.Certificates.Count(), count, "Unexpected number of certificates re-imported.");
            Assert.IsNotNull(imported.GetPrivateKey(certificate), "Failed to get private key after re-importing.");
        }
        public void TestArgumentExceptions()
        {
            var store = new X509CertificateStore();

            Assert.Throws <ArgumentNullException> (() => store.Add(null));
            Assert.Throws <ArgumentNullException> (() => store.AddRange(null));
            Assert.Throws <ArgumentNullException> (() => store.Export((Stream)null, "password"));
            Assert.Throws <ArgumentNullException> (() => store.Export((string)null, "password"));
            Assert.Throws <ArgumentNullException> (() => store.Export(Stream.Null, null));
            Assert.Throws <ArgumentNullException> (() => store.Export("fileName", null));
            Assert.Throws <ArgumentNullException> (() => store.Export((Stream)null));
            Assert.Throws <ArgumentNullException> (() => store.Export((string)null));
            Assert.Throws <ArgumentNullException> (() => store.GetPrivateKey(null));
            Assert.Throws <ArgumentNullException> (() => store.Import((Stream)null, "password"));
            Assert.Throws <ArgumentNullException> (() => store.Import((string)null, "password"));
            Assert.Throws <ArgumentNullException> (() => store.Import((byte[])null, "password"));
            Assert.Throws <ArgumentNullException> (() => store.Import(Stream.Null, null));
            Assert.Throws <ArgumentNullException> (() => store.Import(GetTestDataPath("smime.p12"), null));
            Assert.Throws <ArgumentNullException> (() => store.Import(new byte[0], null));
            Assert.Throws <ArgumentNullException> (() => store.Import((Stream)null));
            Assert.Throws <ArgumentNullException> (() => store.Import((string)null));
            Assert.Throws <ArgumentNullException> (() => store.Import((byte[])null));
            Assert.Throws <ArgumentNullException> (() => store.Remove(null));
            Assert.Throws <ArgumentNullException> (() => store.RemoveRange(null));
        }
Example #4
0
        /**
         * sets proxy for all webrequests
         * opens current user's SSL certificates store
         */
        public static void LoadHttpConfig()
        {
            Trace.WriteLine("Loading proxy settings");
            try
            {
                _defaultProxy = LoadDefaultProxy();
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error loading default proxy settings: " + ex);
            }
            GlobalProxySelection.Select = DefaultProxy;

            X509CertificateStore store =
                X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);

            if (store.OpenRead())
            {
                _certificates = store.Certificates;
                Trace.WriteLine("Number of current user's certificates: " + _certificates.Count, "HttpReader");
            }
            Trace.WriteLine("Default connection limit: " + ServicePointManager.DefaultConnectionLimit);
            Trace.WriteLine("Max service point idle time: " + ServicePointManager.MaxServicePointIdleTime);
            Trace.WriteLine("Max service points: " + ServicePointManager.MaxServicePoints);
        }
        private static X509SecurityToken RetrieveTokenFromStore(X509CertificateStore store, string keyIdentifier)
        {
            if (store == null)
            {
                throw new ArgumentNullException("store");
            }

            X509SecurityToken token = null;

            try
            {
                if (store.OpenRead())
                {
                    // Place the key ID of the certificate in a byte array
                    // This KeyID represents the Wse2Quickstart certificate included with the WSE 2.0 Quickstarts
                    // ClientBase64KeyId is defined in the ClientBase.AppBase class
                    X509CertificateCollection certs = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(keyIdentifier));

                    if (certs.Count > 0)
                    {
                        // Get the first certificate in the collection
                        token = new X509SecurityToken(((X509Certificate)certs[0]));
                    }
                }
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }

            return(token);
        }
Example #6
0
        private X509SecurityToken getToken(string which)
        {
            X509SecurityToken    token = null;
            X509CertificateStore store = null;

            string serverKeyIdentifier = "bBwPfItvKp3b6TNDq+14qs58VJQ=";             //"po3h4Y4J8ITs/pW3acuRjpT8V1o=";
            string clientKeyIdentifier = "gBfo0147lM6cKnTbbMSuMVvmFY4=";             //"Gu4aD7+bYTVtmSveoPIWTRtzD3M=";

            //string serverKeyIdentifier = "po3h4Y4J8ITs/pW3acuRjpT8V1o=";
            //string clientKeyIdentifier = "Gu4aD7+bYTVtmSveoPIWTRtzD3M=";

            store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);
            store.OpenRead();
            X509CertificateCollection coll;

            if (which == "server")
            {
                coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(serverKeyIdentifier));
            }
            else
            {
                coll = store.FindCertificateByKeyIdentifier(Convert.FromBase64String(clientKeyIdentifier));
            }

            if (coll.Count > 0)
            {
                X509Certificate cert = (X509Certificate)coll[0];
                RSA             rsa  = cert.Key;
                token = new X509SecurityToken(cert);
            }
            return(token);
        }
Example #7
0
        public async Task VerifyAppCertX509Store(string storePath)
        {
            var appCertificate = GetTestCert();

            Assert.NotNull(appCertificate);
            Assert.True(appCertificate.HasPrivateKey);
            appCertificate.AddToStore(
                CertificateStoreType.X509Store,
                storePath
                );
            using (var publicKey = new X509Certificate2(appCertificate.RawData))
            {
                Assert.NotNull(publicKey);
                Assert.False(publicKey.HasPrivateKey);

                var id = new CertificateIdentifier()
                {
                    Thumbprint = publicKey.Thumbprint,
                    StorePath  = storePath,
                    StoreType  = CertificateStoreType.X509Store
                };
                var privateKey = await id.LoadPrivateKey(null).ConfigureAwait(false);

                Assert.NotNull(privateKey);
                Assert.True(privateKey.HasPrivateKey);

                X509Utils.VerifyRSAKeyPair(publicKey, privateKey, true);

                using (var x509Store = new X509CertificateStore())
                {
                    x509Store.Open(storePath);
                    await x509Store.Delete(publicKey.Thumbprint).ConfigureAwait(false);
                }
            }
        }
Example #8
0
        public void AddCertificate()
        {
            FileInfo[] files = this.getAllCerts();

            foreach (var file in files)
            {
                System.Security.Cryptography.X509Certificates.X509Certificate2 cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(file.FullName);

                byte[] hashBytes = cert.GetRawCertData();
                X509CertificateStore certstore = new X509CertificateStore();
                certstore.Import(hashBytes);

                IEnumerable <X509Certificate> ix509Cert = certstore.Certificates;
                foreach (var item in ix509Cert)
                {
                    X509Certificate cert2 = item;

                    X509CertificateRecord certrecord = _database.Find(cert2, X509CertificateRecordFields.Certificate);
                    if (certrecord == null)
                    {
                        certrecord = new X509CertificateRecord(cert2);
                        _database.Add(certrecord);
                    }
                }
            }
        }
Example #9
0
        /// <summary>
        /// Retrieve the X509 certificate for a given subject name and location
        /// </summary>
        /// <param name="location">either CurrentUser store or LocalMachine store</param>
        /// <param name="subject">subject name</param>
        /// <returns>X509Certificate object</returns>
        public static X509Certificate SearchCertificateBySubjectName(string location, string subject)
        {
            X509CertificateStore x509Store = null;

            if (location == "CurrentUser")
            {
                x509Store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);
            }
            else
            {
                x509Store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);
            }
            bool            open        = x509Store.OpenRead();
            X509Certificate certificate = null;

            foreach (X509Certificate cert in x509Store.Certificates)
            {
                if (subject.ToUpper() == cert.GetName().ToUpper())
                {
                    certificate = cert;
                    break;
                }
            }
            return(certificate);
        }
      private static X509SecurityToken RetrieveTokenFromStore (X509CertificateStore store, string keyIdentifier) 
	{
	  if (store == null)
	    throw new ArgumentNullException ("store");
	  X509SecurityToken token = null;
	  try 
	    {
	      if (store.OpenRead ())
		{
		  // Place the key ID of the certificate in a byte array
		  // This KeyID represents the Wse2Quickstart certificate included with the WSE 2.0 Quickstarts
		  // ClientBase64KeyId is defined in the ClientBase.AppBase class
		  X509CertificateCollection certs =
		      store.FindCertificateByKeyIdentifier (Convert.FromBase64String (keyIdentifier));
		  if (certs.Count > 0)

		    {
		      // Get the first certificate in the collection
		      token = new X509SecurityToken (((X509Certificate) certs[0]));
		    }
		}
	    }
	  finally 
	    {
	      if (store != null)
		store.Close ();
	    }
	  return token;
	}
Example #11
0
        public SelectCertificateDialog(X509CertificateStore store) : base()
        {
            _store = store;

            // Required for Windows Form Designer support
            //
            InitializeComponent();
        }
Example #12
0
        public static X509SecurityToken GetClientToken()
        {
            X509SecurityToken token = null;
            // Open the CurrentUser Certificate Store and try MyStore only
            X509CertificateStore store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);

            token = RetrieveTokenFromStore(store, ClientBase64KeyId);
            return(token);
        }
        /**
         * this is the constructor for the GUI, it does the following:
         * 1.  set up the DAO objects to access the local database
         * 2.  add any active meetings in the database to the field in the GUI
         * 3.  extract my X.509 certificate from the local store
         * 4.  instantiate 5 "dummy" resources, add them to resource list
         * */
        public Form1()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //

            dbConnect = "DSN=TotalRecall;UID=TotalRecallUser;PWD=totalrecall;DATABASE=TotalRecall";

            mDAO  = new MeetingDAO(dbConnect);
            pDAO  = new ParticipantDAO(dbConnect);
            rDAO  = new ResourceDAO(dbConnect);
            cDAO  = new ContactDAO(dbConnect);
            cmDAO = new ContextMsgDAO(dbConnect);

            strSelectedMtg = "";
            ArrayList lstMtgs = mDAO.GetMeetingIDs(enuMeetingState.Active);

            foreach (string s in lstMtgs)
            {
                m_boxMtgs.Items.Add(s);
            }

            strMyUrl = "http://localhost/TotalRecall/InfoAgent.asmx?wsdl";

            store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);
            store.OpenRead();

            strMyName = "CN=Omar";
            certCol   = store.FindCertificateBySubjectName(strMyName);

            cert      = (X509Certificate)certCol[0];
            certToken = new X509SecurityToken(cert);

            lstResources = new ArrayList();
            for (int i = 0; i < 5; i++)
            {
                Resource res = new Resource();
                res.ID   = "res" + (i + 1);
                res.Name = "Foo" + (i + 1) + ".txt";
                res.Url  = "file:///c:\\" + res.Name;
                rDAO.AddNewResource(res);
                lstResources.Add(res);
            }

            foreach (Resource r in lstResources)
            {
                m_boxResources.Items.Add(r.ID);
            }
        }
        public void TestImportSingleCertificate()
        {
            var store = new X509CertificateStore();

            store.Import(GetTestDataPath(CertificateAuthorities[0]));
            var certificate = store.Certificates.FirstOrDefault();
            var count       = store.Certificates.Count();

            Assert.AreEqual(1, count, "Unexpected number of certificates imported.");
            Assert.AreEqual("StartCom Certification Authority", certificate.GetCommonName(), "Unexpected CN for certificate.");
        }
        public static X509SecurityToken GetServerToken()
        {
            X509SecurityToken    token = null;
            X509CertificateStore store = null;

            // For server, open the LocalMachine Certificate Store and try Personal store.
            store = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);
            token = RetrieveTokenFromStore(store, ServerBase64KeyId);

            return(token);
        }
        public void TestImportSingleCertificate()
        {
            var store = new X509CertificateStore();

            store.Import(GetTestDataPath(CertificateAuthorities[0]));
            var certificate = store.Certificates.FirstOrDefault();
            var count       = store.Certificates.Count();

            Assert.AreEqual(1, count, "Unexpected number of certificates imported.");
            Assert.AreEqual("*****@*****.**", certificate.GetSubjectEmailAddress(), "Unexpected email address for certificate.");
        }
        /// <summary>
        /// Gets the intermediate certificates.
        /// </summary>
        /// <returns>The intermediate certificates.</returns>
        protected override IX509Store GetIntermediateCertificates()
        {
            var store = new X509CertificateStore();

            foreach (var certificate in certificates)
            {
                store.Add(certificate);
            }

            return(store);
        }
Example #18
0
 protected void OneTimeTearDown()
 {
     foreach (var certStore in CertStores)
     {
         using (var x509Store = new X509CertificateStore())
         {
             x509Store.Open(certStore);
             var collection = x509Store.Enumerate().Result;
             foreach (var cert in collection)
             {
                 if (X509Utils.CompareDistinguishedName(X509StoreSubject, cert.Subject))
                 {
                     x509Store.Delete(cert.Thumbprint).Wait();
                 }
             }
         }
     }
 }
Example #19
0
        public static void TestParser()
        {
            string pfxLocation = @"D:\lol\certificate.pfx";

            pfxLocation = @"D:\username\Desktop\DesktopArchiv\20180329_Desktop\CORMailService\CORMailService\CORMailService\CORMailService_TemporaryKey.pfx";



            System.Security.Cryptography.X509Certificates.X509Certificate2 certificate =
                new System.Security.Cryptography.X509Certificates.X509Certificate2(pfxLocation);


            // Private Key
            if (!certificate.HasPrivateKey)
            {
                throw new System.IO.InvalidDataException("no private key in pfx file.");
            }

            System.Security.Cryptography.RSACng rsa = (System.Security.Cryptography.RSACng)certificate.PrivateKey;



            X509CertificateStore xs = new X509CertificateStore();

            xs.Import(pfxLocation);
            foreach (X509Certificate thisCert in xs.Certificates)
            {
                System.Console.WriteLine(thisCert);
                thisCert.GetPublicKey();

                // var signer = Org.BouncyCastle.Security.SignerUtilities.GetSigner(Sdk.SIGNATURE_ALGORITHM);
            }


            X509CertificateParser certParser = new X509CertificateParser();

            using (var fs = System.IO.File.OpenRead(pfxLocation))
            {
                certParser.ReadCertificate(fs);
            }

            System.Console.WriteLine(certParser);
        }
Example #20
0
        public static X509SecurityToken GetServerToken()
        {
            X509SecurityToken    token = null;
            X509CertificateStore store = null;

            store = X509CertificateStore.CurrentUserStore(X509CertificateStore.OtherPeople);
            token = RetrieveTokenFromStore(store, ServerBase64KeyId);

            //
            // If we failed to retrieve it from the OtherPeople,
            // we now try the MyStore
            //
            if (token == null)
            {
                store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);
                token = RetrieveTokenFromStore(store, ServerBase64KeyId);
            }
            return(token);
        }
        /// <summary>
        ///     Get the certificate from the store as provided by FIS
        /// </summary>
        public X509Certificate GetCertificate(string certificateName)
        {
            X509Certificate cert = null;

            // First check local machine store
            var certificateStore = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);

            certificateStore.OpenRead();
            foreach (X509Certificate certificate in certificateStore.Certificates)
            {
                if (certificate.SimpleDisplayName.EqualsIgnoreCase(certificateName))
                {
                    cert = certificate;
                    break;
                }
            }

            // If not found, check root
            if (cert == null)
            {
                certificateStore = X509CertificateStore.LocalMachineStore(X509CertificateStore.RootStore);
                certificateStore.OpenRead();
                foreach (X509Certificate certificate in certificateStore.Certificates)
                {
                    if (certificate.SimpleDisplayName.EqualsIgnoreCase(certificateName))
                    {
                        cert = certificate;
                        break;
                    }
                }
            }

            certificateStore.Close();
            certificateStore.Dispose();

            if (cert == null)
            {
                _logger.Trace("------------ Error --------------   GetCertificate. Certificate not found");
            }

            return(cert);
        }
        public void EncryptAckResponse()
        {
            //Open the current user certificate store and look for Personal category
            X509CertificateStore localStore = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);

            localStore.OpenRead();

            //Find Vendor A Certificate
            X509CertificateCollection certCollection = localStore.FindCertificateBySubjectString("Vendor B");
            X509Certificate           provCert       = certCollection[0];

            //Create a new security token that is of X509 type
            //Token represent claim (authentication information)
            X509SecurityToken token = new X509SecurityToken(provCert);

            ResponseSoapContext.Current.Security.Tokens.Add(token);

            //Instruct WSE inbound filter to encrypt the message before it is transmitted over wire
            ResponseSoapContext.Current.Security.Elements.Add(new EncryptedData(token));
        }
        public static void EncryptContractNote(STPProvider.PostTradeServiceWse postTradeSvc)
        {
            //Open the current user certificate store and look for Personal category
            X509CertificateStore localStore = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);

            localStore.OpenRead();

            //Find STP-Provider A Certificate
            X509CertificateCollection certCollection = localStore.FindCertificateBySubjectString("STP-Provider A");
            X509Certificate           provCert       = certCollection[0];

            //Create a new security token that is of X509 type
            //Token represent claim (authentication information)
            X509SecurityToken token = new X509SecurityToken(provCert);

            postTradeSvc.RequestSoapContext.Security.Tokens.Add(token);

            //Instruct WSE inbound filter to encrypt the message before it is transmitted over wire
            postTradeSvc.RequestSoapContext.Security.Elements.Add(new EncryptedData(token));
        }
Example #24
0
        /// <summary>
        /// Returns the X.509 SecurityToken that will be used to encrypt the
        /// messages.
        /// </summary>
        /// <returns>Returns </returns>
        public X509SecurityToken GetEncryptionToken()
        {
            X509SecurityToken token = null;
            //
            // The certificate for the target receiver should have been imported
            // into the "My" certificate store. This store is listed as "Personal"
            // in the Certificate Manager
            //
            X509CertificateStore store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);
            bool open = store.OpenRead();

            try
            {
                //
                // Open a dialog to allow user to select the certificate to use
                //
                StoreDialog     dialog = new StoreDialog(store);
                X509Certificate cert   = dialog.SelectCertificate(IntPtr.Zero, "Select Certificate", "Choose a Certificate below for encrypting.");
                if (cert == null)
                {
                    throw new ApplicationException("You chose not to select an X509 certificate for encrypting your messages.");
                }
                else if (!cert.SupportsDataEncryption)
                {
                    throw new ApplicationException("The certificate must support key encipherment.");
                }
                else
                {
                    token = new X509SecurityToken(cert);
                }
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }

            return(token);
        }
        public static bool VerifySignFM(byte[] data, byte[] signedData)
        {
            //Open STP certificate store
            X509CertificateStore store = X509CertificateStore.CurrentUserStore("STPCertificateStore");

            store.OpenRead();
            //retrieve broker certificate
            X509Certificate brokerCertificate = store.Certificates[0];

            Console.WriteLine("Certificate Subject :" + brokerCertificate.FriendlyDisplayName);
            Console.WriteLine("Valid From :" + brokerCertificate.GetEffectiveDateString());
            Console.WriteLine("Valid To :" + brokerCertificate.GetExpirationDateString());
            Console.WriteLine("Serial No:" + brokerCertificate.GetSerialNumberString());
            //initialize RSA to use public key stored in broker certificate
            RSAParameters            publicParam = brokerCertificate.Key.ExportParameters(false);
            RSACryptoServiceProvider rsCrypto    = new RSACryptoServiceProvider();

            rsCrypto.ImportParameters(publicParam);
            //verify digital signature
            return(rsCrypto.VerifyData(data, new SHA1Managed(), signedData));
        }
Example #26
0
        /// <summary>
        /// Gets the security token for signing messages.
        /// </summary>
        /// <returns>Returns </returns>
        public X509SecurityToken GetSecurityToken()
        {
            X509SecurityToken securityToken;
            //
            // open the current user's certificate store
            //
            X509CertificateStore store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);
            bool open = store.OpenRead();

            try
            {
                //
                // Open a dialog to allow user to select the certificate to use
                //
                StoreDialog     dialog = new StoreDialog(store);
                X509Certificate cert   = dialog.SelectCertificate(IntPtr.Zero, "Select Certificate", "Choose a Certificate below for signing.");
                if (cert == null)
                {
                    throw new ApplicationException("You chose not to select an X509 certificate for signing your messages.");
                }
                else if (!cert.SupportsDigitalSignature)
                {
                    throw new ApplicationException("The certificate must support digital signatures and have a private key available.");
                }
                else
                {
                    securityToken = new X509SecurityToken(cert);
                }
            }
            finally
            {
                if (store != null)
                {
                    store.Close();
                }
            }
            return(securityToken);
        }
        public void TestAddRemove()
        {
            var certificates = new List <X509Certificate> ();
            var parser       = new X509CertificateParser();
            var store        = new X509CertificateStore();

            foreach (var authority in CertificateAuthorities)
            {
                var path = GetTestDataPath(authority);

                using (var stream = File.OpenRead(path)) {
                    foreach (X509Certificate certificate in parser.ReadCertificates(stream))
                    {
                        certificates.Add(certificate);
                    }
                }
            }

            foreach (var certificate in certificates)
            {
                store.Add(certificate);
            }

            var count = store.Certificates.Count();

            Assert.AreEqual(CertificateAuthorities.Length, count, "Unexpected number of certificates after Add.");

            foreach (var certificate in certificates)
            {
                var key = store.GetPrivateKey(certificate);
                Assert.IsNull(key, "GetPrivateKey");
                store.Remove(certificate);
            }

            count = store.Certificates.Count();

            Assert.AreEqual(0, count, "Unexpected number of certificates after Remove.");
        }
        public void TestImportExportMultipleCertificates()
        {
            var store = new X509CertificateStore();

            foreach (var authority in CertificateAuthorities)
            {
                store.Import(GetTestDataPath(authority));
            }

            var count = store.Certificates.Count();

            Assert.AreEqual(CertificateAuthorities.Length, count, "Unexpected number of certificates imported.");

            store.Export("exported.crt");

            var imported = new X509CertificateStore();

            imported.Import("exported.crt");

            count = imported.Certificates.Count();

            Assert.AreEqual(CertificateAuthorities.Length, count, "Unexpected number of certificates re-imported.");
        }
        public X509Certificate GetContactCertificate(string strContactID)
        {
            X509CertificateStore certStore = X509CertificateStore.LocalMachineStore(X509CertificateStore.MyStore);

            if (certStore == null)
            {
                throw new Exception("Error opening Local Machine Store");
            }

            X509Certificate cert = null;

            if (certStore.OpenRead())
            {
                X509CertificateCollection certColl = certStore.FindCertificateBySubjectName(strContactID);
                if (certColl.Count == 1)
                {
                    cert = certColl[0];
                }
            }

            // Close the certificate store
            certStore.Close();
            return(cert);
        }
 public StoreDialog(X509CertificateStore store)
 {
     this.store = store;
 }
        public SelectCertificateDialog(X509CertificateStore store) : base()
        {
            _store = store;

            // Required for Windows Form Designer support
            //
            InitializeComponent();
        }
Example #32
0
    /// <summary>
    /// Creates a self signed application instance certificate.
    /// </summary>
    /// <param name="storeType">Type of certificate store (Directory) <see cref="CertificateStoreType"/>.</param>
    /// <param name="storePath">The store path (syntax depends on storeType).</param>
    /// <param name="password">The password to use to protect the certificate.</param>
    /// <param name="applicationUri">The application uri (created if not specified).</param>
    /// <param name="applicationName">Name of the application (optional if subjectName is specified).</param>
    /// <param name="subjectName">The subject used to create the certificate (optional if applicationName is specified).</param>
    /// <param name="domainNames">The domain names that can be used to access the server machine (defaults to local computer name if not specified).</param>
    /// <param name="keySize">Size of the key (1024, 2048 or 4096).</param>
    /// <param name="startTime">The start time.</param>
    /// <param name="lifetimeInMonths">The lifetime of the key in months.</param>
    /// <param name="hashSizeInBits">The hash size in bits.</param>
    /// <param name="isCA">if set to <c>true</c> then a CA certificate is created.</param>
    /// <param name="issuerCAKeyCert">The CA cert with the CA private key.</param>
    /// <returns>The certificate with a private key.</returns>
    public static X509Certificate2 CreateCertificate(
        string storeType,
        string storePath,
        string password,
        string applicationUri,
        string applicationName,
        string subjectName,
        IList <String> domainNames,
        ushort keySize,
        DateTime startTime,
        ushort lifetimeInMonths,
        ushort hashSizeInBits,
        bool isCA,
        X509Certificate2 issuerCAKeyCert)
    {
        if (issuerCAKeyCert != null)
        {
            if (!issuerCAKeyCert.HasPrivateKey)
            {
                throw new NotSupportedException("Cannot sign with a CA certificate without a private key.");
            }
        }

        // set default values.
        X509Name subjectDN = SetSuitableDefaults(
            ref applicationUri,
            ref applicationName,
            ref subjectName,
            ref domainNames,
            ref keySize,
            ref lifetimeInMonths,
            isCA);

        using (var cfrg = new CertificateFactoryRandomGenerator())
        {
            // cert generators
            SecureRandom random           = new SecureRandom(cfrg);
            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            // Serial Number
            BigInteger serialNumber = BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random);
            cg.SetSerialNumber(serialNumber);

            X509Name issuerDN = null;
            if (issuerCAKeyCert != null)
            {
                issuerDN = new X509Name(true, issuerCAKeyCert.Subject.Replace("S=", "ST="));
            }
            else
            {
                // self signed
                issuerDN = subjectDN;
            }

            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);

            // valid for
            cg.SetNotBefore(startTime);
            cg.SetNotAfter(startTime.AddMonths(lifetimeInMonths));

            // Private/Public Key
            AsymmetricCipherKeyPair subjectKeyPair;
            var keyGenerationParameters = new KeyGenerationParameters(random, keySize);
            var keyPairGenerator        = new RsaKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            subjectKeyPair = keyPairGenerator.GenerateKeyPair();
            cg.SetPublicKey(subjectKeyPair.Public);

            // add extensions
            // Subject key identifier
            cg.AddExtension(X509Extensions.SubjectKeyIdentifier.Id, false,
                            new SubjectKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public)));

            // Basic constraints
            cg.AddExtension(X509Extensions.BasicConstraints.Id, true, new BasicConstraints(isCA));

            // Authority Key identifier
            var issuerKeyPair      = subjectKeyPair;
            var issuerSerialNumber = serialNumber;
            cg.AddExtension(X509Extensions.AuthorityKeyIdentifier.Id, false,
                            new AuthorityKeyIdentifier(SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(subjectKeyPair.Public),
                                                       new GeneralNames(new GeneralName(issuerDN)), issuerSerialNumber));

            if (!isCA)
            {
                // Key usage
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.DataEncipherment | KeyUsage.DigitalSignature |
                                             KeyUsage.NonRepudiation | KeyUsage.KeyCertSign | KeyUsage.KeyEncipherment));

                // Extended Key usage
                cg.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                new ExtendedKeyUsage(new List <DerObjectIdentifier>()
                {
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.1"), // server auth
                    new DerObjectIdentifier("1.3.6.1.5.5.7.3.2"), // client auth
                }));

                // subject alternate name
                cg.AddExtension(X509Extensions.SubjectAlternativeName, false,
                                new GeneralNames(new GeneralName[] {
                    new GeneralName(GeneralName.UniformResourceIdentifier, applicationUri),
                    new GeneralName(GeneralName.DnsName, domainNames[0])
                }));
            }
            else
            {
                // Key usage CA
                cg.AddExtension(X509Extensions.KeyUsage, true,
                                new KeyUsage(KeyUsage.CrlSign | KeyUsage.DigitalSignature | KeyUsage.KeyCertSign));
            }

            // sign certificate
            AsymmetricKeyParameter privateKey = null;
            if (issuerCAKeyCert != null)
            {
                using (RSA rsa = issuerCAKeyCert.GetRSAPrivateKey())
                {
                    RSAParameters rsaParams = rsa.ExportParameters(true);
                    RsaPrivateCrtKeyParameters keyParams = new RsaPrivateCrtKeyParameters(
                        new BigInteger(1, rsaParams.Modulus),
                        new BigInteger(1, rsaParams.Exponent),
                        new BigInteger(1, rsaParams.D),
                        new BigInteger(1, rsaParams.P),
                        new BigInteger(1, rsaParams.Q),
                        new BigInteger(1, rsaParams.DP),
                        new BigInteger(1, rsaParams.DQ),
                        new BigInteger(1, rsaParams.InverseQ));
                    privateKey = keyParams;
                }
            }
            else
            {
                privateKey = subjectKeyPair.Private;
            }

            ISignatureFactory signatureFactory =
                new Asn1SignatureFactory((hashSizeInBits < 256) ? "SHA1WITHRSA" : "SHA256WITHRSA", privateKey, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create pkcs12 store for cert and private key
            X509Certificate2 certificate = null;
            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12Store            pkcsStore = new Pkcs12StoreBuilder().Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = Guid.NewGuid().ToString();
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(applicationName, new AsymmetricKeyEntry(subjectKeyPair.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // merge into X509Certificate2
                certificate = CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);
            }

            Utils.Trace(Utils.TraceMasks.Security, "Created new certificate: {0}", certificate.Thumbprint);

            // add cert to the store.
            if (!String.IsNullOrEmpty(storePath))
            {
                ICertificateStore store = null;
                if (storeType == CertificateStoreType.X509Store)
                {
                    store = new X509CertificateStore();
                }
                else if (storeType == CertificateStoreType.Directory)
                {
                    store = new DirectoryCertificateStore();
                }
                else
                {
                    throw new ArgumentException("Invalid store type");
                }

                store.Open(storePath);
                store.Add(certificate, password);
                store.Close();
                store.Dispose();
            }

            // note: this cert has a private key!
            return(certificate);
        }
    }
Example #33
0
 public StoreDialog(X509CertificateStore store)
 {
     this.store = store;
 }