public void TestSecureStringToChars()
 {
     foreach (SecureString ss in MakeStrings())
     {
         Assert.AreEqual(TEST_PASSWORD, new String(SecureStringUtils.ToCharArray(ss)));
     }
 }
Beispiel #2
0
        public void TestConstruction()
        {
            using (PasswordHash pwd1 = new PasswordHash(TEST_PASSWORD))
            {
                //no salt provided
                using (PasswordHash pwd2 = new PasswordHash(TEST_PASSWORD))
                    Assert.AreNotEqual(pwd1, pwd2);
                using (PasswordHash pwd2 = new PasswordHash(false, Password.Encoding.GetBytes(TEST_PASSWORD)))
                    Assert.AreNotEqual(pwd1, pwd2);
                //identical salt
                using (PasswordHash pwd2 = new PasswordHash(TEST_PASSWORD, pwd1.Salt))
                    Assert.AreEqual(pwd1, pwd2);
                using (PasswordHash pwd2 = new PasswordHash(false, Password.Encoding.GetBytes(TEST_PASSWORD), pwd1.Salt))
                    Assert.AreEqual(pwd1, pwd2);
                using (PasswordHash pwd2 = new PasswordHash(new MemoryStream(Password.Encoding.GetBytes(TEST_PASSWORD)), pwd1.Salt))
                    Assert.AreEqual(pwd1, pwd2);

                using (PasswordHash pwd2 = new PasswordHash(new Password(TEST_PASSWORD), pwd1.Salt))
                    Assert.AreEqual(pwd1, pwd2);
                using (SecureString sstr = SecureStringUtils.Create(TEST_PASSWORD))
                {
                    using (PasswordHash pwd2 = new PasswordHash(sstr, pwd1.Salt))
                        Assert.AreEqual(pwd1, pwd2);
                    using (PasswordHash pwd2 = new PasswordHash(sstr))
                        Assert.AreNotEqual(pwd1, pwd2);
                }
            }
        }
        public void TestSecureStringReader()
        {
            foreach (SecureString ss in MakeStrings())
            {
                Assert.AreEqual(TEST_PASSWORD, SecureStringUtils.ToTextReader(ss).ReadToEnd());

                StringBuilder sb = new StringBuilder();
                using (TextReader r = SecureStringUtils.ToTextReader(ss))
                {
                    while (r.Peek() != -1)
                    {
                        sb.Append((char)r.Read());
                        int i = r.Read();
                        if (i != -1)
                        {
                            sb.Append((char)i);
                        }
                    }
                }
                Assert.AreEqual(TEST_PASSWORD, sb.ToString());

                char[] buffer = new char[TEST_PASSWORD.Length];
                using (TextReader r = new UnicodeReader(SecureStringUtils.ToStream(ss)))
                {
                    for (int i = 0; i < buffer.Length; i++)
                    {
                        Assert.AreEqual(1, r.ReadBlock(buffer, i, buffer.Length - i));
                    }
                    Assert.AreEqual(0, r.ReadBlock(buffer, 0, buffer.Length));
                }
                Assert.AreEqual(TEST_PASSWORD, new string(buffer));
            }
        }
 public void TestSecureStringToByteArray()
 {
     foreach (SecureString ss in MakeStrings())
     {
         Assert.AreEqual(Encoding.Unicode.GetBytes(TEST_PASSWORD), SecureStringUtils.ToByteArray(ss));
         Assert.AreEqual(Encoding.UTF8.GetBytes(TEST_PASSWORD), SecureStringUtils.ToByteArray(ss, Encoding.UTF8));
     }
 }
 public void TestSecureStringToStream()
 {
     byte[] expect = Encoding.Unicode.GetBytes(TEST_PASSWORD);
     foreach (SecureString ss in MakeStrings())
     {
         Assert.AreEqual(expect, IOStream.ReadAllBytes(SecureStringUtils.ToStream(ss)));
         Assert.AreEqual(TEST_PASSWORD, IOStream.ReadAllText(SecureStringUtils.ToStream(ss), Encoding.Unicode));
     }
 }
        IEnumerable <SecureString> MakeStrings()
        {
            yield return(SecureStringUtils.Create(TEST_PASSWORD));

            yield return(SecureStringUtils.Create(TEST_PASSWORD.ToCharArray()));

            yield return(SecureStringUtils.Create(new MemoryStream(Encoding.Unicode.GetBytes(TEST_PASSWORD))));

            yield return(SecureStringUtils.Create(new MemoryStream(Encoding.UTF8.GetBytes(TEST_PASSWORD)), Encoding.UTF8));

            yield return(SecureStringUtils.AppendAll(new SecureString(), TEST_PASSWORD));
        }
        public void TestSecureStringCopyChars()
        {
            foreach (SecureString ss in MakeStrings())
            {
                char[] temp = new char[TEST_PASSWORD.Length];
                SecureStringUtils.CopyChars(ss, 0, temp, 0, temp.Length);
                Assert.AreEqual(TEST_PASSWORD, new String(temp));

                temp = new char[TEST_PASSWORD.Length];
                SecureStringUtils.CopyChars(ss, 4, temp, 4, temp.Length - 4);
                Assert.AreNotEqual(TEST_PASSWORD, new String(temp));
                SecureStringUtils.CopyChars(ss, 0, temp, 0, 4);
                Assert.AreEqual(TEST_PASSWORD, new String(temp));
            }
        }
        public void TestRecreate()
        {
            PasswordKey pk1 = new PasswordKey(TEST_PASSWORD);
            PasswordKey pk2 = new PasswordKey(SecureStringUtils.Create(TEST_PASSWORD));

            Assert.AreNotEqual(pk1.CreateKey().Key, pk2.CreateKey().Key);

            pk2.Salt = pk1.Salt;
            Assert.AreEqual(pk1.CreateKey().Key, pk2.CreateKey().Key);
            pk1.CreateKey();
            Assert.AreEqual(pk1.CreateKey().Key, pk2.CreateKey().Key);

            pk1.Salt = new Salt();
            Assert.AreNotEqual(pk1.Salt, pk2.Salt);
            Assert.AreNotEqual(pk1.CreateKey().Key, pk2.CreateKey().Key);
            Assert.AreEqual(pk1.CreateKey().Key, pk2.CreateKey(pk1.Salt).Key);
            pk2.Salt = pk1.Salt;
            Assert.AreEqual(pk1.Salt, pk2.Salt);
            Assert.AreEqual(pk1.CreateKey().Key, pk2.CreateKey().Key);
        }
        /// <summary>
        /// Uses PBKD2 to derive a 3DES key and decrypts data
        /// </summary>
        private byte[] DecryptPBDK2(byte[] edata, byte[] salt, byte[] IV, SecureString securePassword, int iterations)
        {
            byte[] psbytes = SecureStringUtils.Decrypt(securePassword);

            var rfc2898DeriveBytes = new Rfc2898DeriveBytes(psbytes, salt, iterations);

            var decAlg = TripleDES.Create();

            decAlg.Key = rfc2898DeriveBytes.GetBytes(24);
            decAlg.IV  = IV;

            var memoryStream = new MemoryStream();

            using (var decrypt = new CryptoStream(memoryStream, decAlg.CreateDecryptor(), CryptoStreamMode.Write))
            {
                decrypt.Write(edata, 0, edata.Length);
                decrypt.Flush();
                // decrypt.Close(); // this is REQUIRED ?
            }

            return(memoryStream.ToArray());
        }
Beispiel #10
0
        public static void TestX509Certificate2WithEncryptedPrivateKey()
        {
            Console.WriteLine("TestX509Certificate2WithEncryptedPrivateKey");

            // Generated using:
            // openssl req -x509 -sha256 -days 365 -newkey rsa:2048 -keyout pwd_private_temp.key -out pwd_certificate_pub.crt
            // openssl pkcs8 -topk8 -in pwd_private_temp.key -out pwd_private.key
            // password = abc123
            string certificateText = File.ReadAllText("pwd_certificate_pub.crt");
            string privateKeyText  = File.ReadAllText("pwd_private.key");

            ICertificateProvider provider    = new CertificateFromFileProvider(certificateText, privateKeyText, SecureStringUtils.Encrypt("abc123"));
            X509Certificate2     certificate = provider.Certificate;

            Console.WriteLine("X509Certificate2:");
            Console.WriteLine(certificate);
            Console.WriteLine();
            Console.WriteLine("PrivateKey:");
            RSACryptoServiceProvider cryptoServiceProvider = (RSACryptoServiceProvider)certificate.PrivateKey;

            ShowRSAProperties(cryptoServiceProvider);

            var xml = XDocument.Parse(cryptoServiceProvider.ToXmlString(true));

            Console.WriteLine(xml.ToString());

            // Sign the data
            byte[] hello     = new UTF8Encoding().GetBytes("Hello World");
            byte[] hashValue = cryptoServiceProvider.SignData(hello, CryptoConfig.MapNameToOID("SHA256"));

            RSACryptoServiceProvider publicKey = provider.PublicKey;
            bool verifyHashResult = publicKey.VerifyData(hello, CryptoConfig.MapNameToOID("SHA256"), hashValue);

            Console.WriteLine();
            Console.WriteLine("VerifyHash: {0}", verifyHashResult);
        }
Beispiel #11
0
        private async void btnUpload_Click(object sender, EventArgs e)
        {
            log.Info("btnUpload_Click");
            if (!bWork)
            {
                this.pbUpload.Value          = 0;
                tokenSource                  = new CancellationTokenSource();
                this.btnCancelUplaod.Enabled = false;
                bWork = true;
                string host        = string.Empty;
                string user        = string.Empty;
                string strPassWord = string.Empty;
                try
                {
                    if (!File.Exists(Application.UserAppDataPath + "\\seafileaddin.cfg"))
                    {
                        log.Error("seafileaddin.cfg not exits");
                        MessageBox.Show(
                            Properties.Resources.SetAccount,
                            Properties.Resources.MessageBoxErrorTitle,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                        //MessageBox.Show("An error occurred while attempting to show the application." +
                        //            "The error is:" + Properties.Resources.SetAccount);
                        this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                        this.Close();

                        return;
                    }

                    using (var file = File.OpenText(Application.UserAppDataPath + "\\seafileaddin.cfg"))
                    {
                        using (JsonTextReader reader = new JsonTextReader(file))
                        {
                            JObject o2 = (JObject)JToken.ReadFrom(reader);
                            host        = (string)o2["accessurl"];
                            user        = (string)o2["account"];
                            strPassWord = DataProtectionExtensions.Unprotect((string)o2["poassword"]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    MessageBox.Show(
                        Properties.Resources.ConfigParseError,
                        Properties.Resources.MessageBoxErrorTitle,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);

                    this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                    this.Close();

                    //
                    return;
                }



                if (string.IsNullOrEmpty(tbFile.Text))
                {
                    MessageBox.Show(
                        Properties.Resources.EmptyUploadFile,
                        Properties.Resources.MessageBoxInfoTitle,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Information);
                    this.btnCancelUplaod.Enabled = true;
                    bWork = false;
                    return;
                }



                string strPassword = string.Empty;
                string strExpire   = string.Empty;
                if (cbPassword.Checked)
                {
                    if (string.IsNullOrEmpty(this.tbPassword.Text))
                    {
                        MessageBox.Show(
                            Properties.Resources.EmptyPassword,
                            Properties.Resources.MessageBoxInfoTitle,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                        this.btnCancelUplaod.Enabled = true;
                        bWork = false;
                        return;
                    }

                    if (this.tbPassword.Text.Length < 8)
                    {
                        MessageBox.Show(
                            Properties.Resources.PasswordTooShort,
                            Properties.Resources.MessageBoxInfoTitle,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                        this.btnCancelUplaod.Enabled = true;
                        bWork = false;
                        return;
                    }

                    if (this.tbPassword.Text != this.tbPasswordR.Text)
                    {
                        MessageBox.Show(
                            Properties.Resources.PasswordNotMatch,
                            Properties.Resources.MessageBoxInfoTitle,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
                        this.btnCancelUplaod.Enabled = true;
                        bWork = false;
                        return;
                    }
                    strPassword = this.tbPassword.Text;
                }

                if (cbExpire.Checked)
                {
                    if (string.IsNullOrEmpty(this.tbExpireDay.Text))
                    {
                        this.btnCancelUplaod.Enabled = true;
                        bWork = false;
                        return;
                    }
                    strExpire = this.tbExpireDay.Text;
                }



                System.Net.ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, errors) =>
                {
                    return(true);
                };


                char[]       pChar = strPassWord.ToCharArray();
                SecureString pw    = new SecureString();

                foreach (char c in pChar)
                {
                    pw.AppendChar(c);
                }

                char[] pwBuf = SecureStringUtils.SecureStringToCharArray(pw);
                pw.Dispose();

                try
                {
                    session = await SeafileSession.Establish(new Uri(host, UriKind.Absolute), user, pwBuf);

                    // try to connect to the seafile server using the given credentials
                    log.Info("connection success.");


                    this.btnCancelUplaod.Enabled = true;
                    this.btnCancelUplaod.Text    = Properties.Resources.Cancel;


                    //TODO loading process...
                    var seafDefaultLibrary = await session.GetDefaultLibrary();


                    try
                    {
                        var exit = await session.ListDirectory(seafDefaultLibrary, "/outlook");
                    }
                    catch (SeafException exListDirectory)
                    {
                        log.Info("outlook folder doesn't exit.");
                        if (exListDirectory.SeafError.HttpStatusCode == System.Net.HttpStatusCode.Forbidden)
                        {
                            bool successCreate = await session.CreateDirectory(seafDefaultLibrary, "/outlook");
                        }
                    }
                    //catch (Exception ex)
                    //{
                    //    log.Error(ex.Message);

                    //    MessageBox.Show(ex.Message, Properties.Resources.MessageBoxErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);

                    //    return;

                    //}

                    //check if file exist
                    string fileName = System.IO.Path.GetFileName(tbFile.Text);


                    System.IO.FileStream fs = new System.IO.FileStream(tbFile.Text, System.IO.FileMode.Open);
                    pbUpload.Value = 0;
                    Action <float> ProcessAction = new Action <float>(ProcessCallBack);

                    var resultUploadSingle = await session.UploadSingle(seafDefaultLibrary, "/outlook", fileName, fs, tokenSource.Token, ProcessAction);

                    if (resultUploadSingle != null)
                    {
                        JObject o2 = (JObject)JToken.Parse(resultUploadSingle.Substring(1, resultUploadSingle.Length - 2));

                        string tmpName = (string)o2["name"];

                        SeafDirEntry tmp = new SeafDirEntry();

                        tmp.LibraryId = seafDefaultLibrary.Id;

                        tmp.Path = string.Format("/outlook/{0}", tmpName);

                        var resultCreatShareLink = await session.CreatShareLink(tmp, tokenSource.Token, strPassword, strExpire);

                        if (!string.IsNullOrEmpty(resultCreatShareLink))
                        {
                            this.DialogResult = DialogResult.OK;
                            //this.ShareLink = resultCreatShareLink;
                            JObject oShare = (JObject)JToken.Parse(resultCreatShareLink);
                            this.ShareLink = (string)oShare["link"];
                            if (cbPassword.Checked)
                            {
                                this.ShareLink += string.Format("\r\n {0}:{1}", Properties.Resources.SharePassword, this.tbPassword.Text);
                            }
                        }
                    }
                }
                catch (System.OperationCanceledException ex)
                {
                    log.Info(ex.Message);
                }
                catch (System.IO.IOException ioEx)
                {
                    log.Error(ioEx.Message);
                    MessageBox.Show(
                        Properties.Resources.ReadFileError,
                        Properties.Resources.MessageBoxErrorTitle,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return;
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    MessageBox.Show(ex.Message, Properties.Resources.MessageBoxErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    this.btnCancelUplaod.Enabled = true;
                    this.btnCancelUplaod.Text    = Properties.Resources.UploadBtn;
                    tokenSource.Dispose();
                    bWork = false;
                }
            }
            else
            {
                if (tokenSource != null)
                {
                    tokenSource.Cancel();
                    log.Info("cancel upload.");
                    bWork = false;
                    this.pbUpload.Value = 0;
                }
            }
        }
Beispiel #12
0
        //   private async void tscbLibrary_SelectedIndexChanged(object sender, EventArgs e)
        //   {
        //       if (tscbLibrary.SelectedIndex != -1)
        //       {
        //           if (seafLibrary[tscbLibrary.SelectedIndex].Encrypted)
        //           {
        //               //considering we already have the two modes respectively for settings and options
        //               WindowWrapper objActiveWindow = new WindowWrapper(Globals.ThisAddIn.Application.ActiveWindow());
        //               UI.EnterPasswordForm frmBox = new UI.EnterPasswordForm();
        //               frmBox.ShowDialog(objActiveWindow);

        //               if (frmBox.DialogResult == DialogResult.OK)
        //               {
        //                   bool success = await session.DecryptLibrary(seafLibrary[tscbLibrary.SelectedIndex], frmBox.PassWord.ToCharArray());

        //                   if (!success)
        //                   {
        //                       MessageBox.Show("密码错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //                   }

        //               }
        //               else
        //               {
        //                   return;
        //               }


        //           }
        //           curSeafDirEntry = await session.ListDirectory(seafLibrary[tscbLibrary.SelectedIndex]);
        //           for (int i = 0; i < curSeafDirEntry.Count; i++)
        //           {
        //               ListViewItem lvi = new ListViewItem(curSeafDirEntry[i].Id);

        //               lvi.SubItems.Add(curSeafDirEntry[i].Name);   //后面添加的Item都为SubItems ,即为子项
        //               lvi.SubItems.Add(curSeafDirEntry[i].Size.ToString());
        //               lvi.SubItems.Add(curSeafDirEntry[i].Timestamp.ToString());
        //               lvi.ImageIndex = 0;
        //               if (curSeafDirEntry[i].Type == DirEntryType.Dir)
        //               {
        //                   lvi.ImageIndex = 0;
        //               }
        //               else
        //               {
        //                   lvi.ImageIndex = 1;
        //               }
        //               this.listViewDir.Items.Add(lvi);//最后进行添加
        //           }


        //       }


        //   }

        //private void tsbShare_Click(object sender, EventArgs e)
        //   {
        //       if (listViewDir.SelectedItems.Count > 0)
        //       {
        //           int index = listViewDir.SelectedItems[0].Index;

        //           WindowWrapper objActiveWindow = new WindowWrapper(Globals.ThisAddIn.Application.ActiveWindow());
        //           UI.GenerateShareLinkForm frmBox = new UI.GenerateShareLinkForm(session, curSeafDirEntry[index].Directory);
        //           frmBox.ShowDialog(objActiveWindow);
        //           if (frmBox.DialogResult == DialogResult.OK)
        //           {

        //           }
        //           else
        //           {

        //           }
        //       }
        //   }

        //   private async void listViewDir_MouseDoubleClick(object sender, MouseEventArgs e)
        //   {
        //       if (listViewDir.SelectedItems.Count > 0)
        //       {
        //           int index = listViewDir.SelectedItems[0].Index;

        //           if (curSeafDirEntry != null && curSeafDirEntry[index].Type == DirEntryType.Dir)
        //           {
        //               var temp = await session.ListDirectory(seafLibrary[tscbLibrary.SelectedIndex], curSeafDirEntry[index].Directory);
        //               if (temp != null)
        //               {
        //                   curSeafDirEntry.Clear();
        //                   listViewDir.Clear();
        //                   curSeafDirEntry = temp;

        //                   for (int i = 0; i < curSeafDirEntry.Count; i++)
        //                   {
        //                       if (curSeafDirEntry[i].Type == DirEntryType.Dir)
        //                       {

        //                           ListViewItem lvi = new ListViewItem(curSeafDirEntry[i].Id);

        //                           lvi.SubItems.Add(curSeafDirEntry[i].Name);   //后面添加的Item都为SubItems ,即为子项
        //                           lvi.SubItems.Add(curSeafDirEntry[i].Size.ToString());
        //                           lvi.SubItems.Add(curSeafDirEntry[i].Timestamp.ToString());
        //                           lvi.ImageIndex = 0;
        //                           this.listViewDir.Items.Add(lvi);//最后进行添加
        //                       }

        //                   }
        //               }
        //           }

        //       }
        //   }

        private async void SeafileForm_Load(object sender, EventArgs e)
        {
            this.UseWaitCursor      = true;//from the Form/Window instance
            this.tsbRefresh.Enabled = false;
            this.tsbShare.Enabled   = false;

            System.Net.ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, errors) =>
            {
                return(true);
            };

            string host        = string.Empty;
            string user        = string.Empty;
            string strPassWord = string.Empty;

            try
            {
                if (!File.Exists(Application.UserAppDataPath + "\\seafileaddin.cfg"))
                {
                    log.Error("seafileaddin.cfg not exits");
                    MessageBox.Show(
                        Properties.Resources.SetAccount,
                        Properties.Resources.MessageBoxErrorTitle,
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                    this.Close();
                    return;
                }

                using (var file = File.OpenText(Application.UserAppDataPath + "\\seafileaddin.cfg"))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        JObject o2 = (JObject)JToken.ReadFrom(reader);
                        host        = (string)o2["accessurl"];
                        user        = (string)o2["account"];
                        strPassWord = DataProtectionExtensions.Unprotect((string)o2["poassword"]);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(
                    Properties.Resources.ConfigParseError,
                    Properties.Resources.MessageBoxErrorTitle,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);

                this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
                this.Close();
                return;
            }


            char[]       pChar = strPassWord.ToCharArray();
            SecureString pw    = new SecureString();

            foreach (char c in pChar)
            {
                pw.AppendChar(c);
            }


            char[] pwBuf = SecureStringUtils.SecureStringToCharArray(pw);
            pw.Dispose();

            try
            {
                session = await SeafileSession.Establish(new Uri(host, UriKind.Absolute), user, pwBuf);

                log.Info("connection success.");



                //TODO loading process...
                seafLibrary = await session.ListLibraries();

                IList <string> libList = new List <string>();
                int            i       = 1;
                foreach (var lib in seafLibrary)
                {
                    libList.Add(lib.Name);
                    //System.Windows.Forms.TreeNode treeNode = new System.Windows.Forms.TreeNode(lib.Name);

                    this.seafiledirData.SeafileDataTable.AddSeafileDataTableRow(i.ToString(), lib.Name, "", lib.Id, ((int)(DirType.Library)).ToString(), "");
                    i++;
                }
                this.tvDir.ExpandAll();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(ex.Message, Properties.Resources.MessageBoxErrorTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.tsbRefresh.Enabled = false;
                this.tsbShare.Enabled   = false;
                this.UseWaitCursor      = false;
            }
        }
Beispiel #13
0
        private async void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                this.UseWaitCursor = true;

                string strPassword = string.Empty;
                string strExpire   = string.Empty;


                System.Net.ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, errors) =>
                {
                    return(true);
                };


                char[]       pChar = this.tbPassword.Text.ToCharArray();
                SecureString pw    = new SecureString();

                foreach (char c in pChar)
                {
                    pw.AppendChar(c);
                }

                char[] pwBuf = SecureStringUtils.SecureStringToCharArray(pw);
                pw.Dispose();

                try
                {
                    SeafileSession session = await SeafileSession.Establish(new Uri(this.tbURL.Text, UriKind.Absolute), this.tbAccount.Text, pwBuf);
                }
                catch (SeafException se)
                {
                    log.Error(se.SeafError.GetErrorMessage());
                    //SeafileClient.Types.SeafErrorCode.InvalidCredentials
                    if (se.SeafError.SeafErrorCode == SeafileClient.Types.SeafErrorCode.InvalidCredentials)
                    {
                        MessageBox.Show(
                            Properties.Resources.InvalidCredentials,
                            Properties.Resources.MessageBoxErrorTitle,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }
                    else
                    {
                        MessageBox.Show(
                            se.SeafError.GetErrorMessage(),
                            Properties.Resources.MessageBoxErrorTitle,
                            MessageBoxButtons.OK,
                            MessageBoxIcon.Error);
                    }
                    return;
                }

                string encryptedPassword = DataProtectionExtensions.Protect(this.tbPassword.Text);
                string decryptedPassword = DataProtectionExtensions.Unprotect(encryptedPassword);
                // Create a file that the application will store user specific data in.
                using (var file = File.CreateText(Application.UserAppDataPath + "\\seafileaddin.cfg"))
                {
                    JObject objSetting = new JObject(
                        new JProperty("accessurl", this.tbURL.Text),
                        new JProperty("account", this.tbAccount.Text),
                        new JProperty("poassword", encryptedPassword));
                    using (JsonTextWriter writer = new JsonTextWriter(file))
                    {
                        objSetting.WriteTo(writer);
                    }

                    this.DialogResult = DialogResult.OK;
                }
            }
            catch (IOException ex)
            {
                log.Error(ex.Message);
                MessageBox.Show(
                    ex.Message,
                    Properties.Resources.MessageBoxErrorTitle,
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            finally
            {
                this.UseWaitCursor = false;
            }
        }