Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Beispiel #1
0
        private int[] 親からランダムな交叉(int[] geneA, int[] geneB, int パラメータ数)
        {
            //Int32と同じサイズのバイト配列にランダムな値を設定する
            //byte[] bs = new byte[sizeof(int)];
            byte[] bs = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bs);
            //Int32に変換する
            int seed = System.BitConverter.ToInt32(bs, 0);
            // そのseedを基にRandomを作る
            var r = new Random(seed++);

            int[] gene = new int[パラメータ数 + 他の要素];

            for (int i = 0; i < パラメータ数; i++)
            {
                if (r.Next(2) == 1)
                {
                    gene[i] = geneA[i];
                }
                else
                {
                    gene[i] = geneB[i];
                }
            }
            bs = null;
            rng.Dispose();
            r = null;
            return(gene);
        }
Beispiel #2
0
        private int[] ランダムに遺伝子1つ作成(int[,] パラメータ)
        {
            int パラメータ数 = パラメータ.Length / 2;

            //Int32と同じサイズのバイト配列にランダムな値を設定する
            //byte[] bs = new byte[sizeof(int)];
            byte[] bs = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bs);
            //Int32に変換する
            int seed = System.BitConverter.ToInt32(bs, 0);
            // そのseedを基にRandomを作る
            var r = new Random(seed++);

            int[] gene = new int[パラメータ数 + 他の要素];

            for (int i = 0; i < パラメータ数; i++)
            {
                gene[i] = r.Next(パラメータ[i, 0], パラメータ[i, 1] + 1);
            }
            bs = null;
            rng.Dispose();
            r = null;
            return(gene);
        }
Beispiel #3
0
        public Server()
        {
            this.name = String.Empty;

            this.sqlHost = String.Empty;
            this.sqlPort = 3306;
            this.sqlUser = String.Empty;
            this.sqlPassword = String.Empty;

            this.sshHost = String.Empty;
            this.sshPort = 22;
            this.sshUser = String.Empty;
            this.sshPassword = String.Empty;
            this.useSSHTunnel = false;

            RNGCryptoServiceProvider sqlRng = new RNGCryptoServiceProvider();
            byte[] sqlBuffer = new byte[1024];

            sqlRng.GetBytes(sqlBuffer);
            this.sqlEntropy = BitConverter.ToString(sqlBuffer);
            sqlRng.Dispose();

            RNGCryptoServiceProvider sshRng = new RNGCryptoServiceProvider();
            byte[] sshBuffer = new byte[1024];

            sshRng.GetBytes(sshBuffer);
            this.sshEntropy = BitConverter.ToString(sshBuffer);
            sshRng.Dispose();

            this._encryptedSqlPassword = String.Empty;
            this._encryptedSshPassword = String.Empty;
        }
        /// <summary>
        /// Generate a random string of characters
        /// </summary>
        /// <param name="length">length of string</param>
        /// <param name="type">type of string to be generated</param>
        /// <returns></returns>
        public static string GenerateRandomString(int length, StringType type)
        {
            switch (type)
            {
                case StringType.AlphaNumeric:
                    string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
                    char[] chars = new char[length];
                    Random rd = new Random();

                    for (int i = 0; i < length; i++)
                    {
                        chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
                    }

                    return new string(chars);
                    break;

                case StringType.AlphaNumericSymbol:
                    //Generate a cryptographic random number.
                    var rng = new RNGCryptoServiceProvider();
                    var buff = new byte[length];
                    rng.GetBytes(buff);

                    rng.Dispose();

                    // Return a Base64 string representation of the random number.
                    return Convert.ToBase64String(buff);
                    break;
                default:
                    throw new ArgumentException("Type not supported");
            }
        }
Beispiel #5
0
            public static string ComputeHash(string plaintext, Supported_HA hash, byte[] salt)
            {
                int minSaltLength = 4;
                int maxSaltLenght = 6;
                byte[] SaltBytes = null;

                if(salt!=null)
                {
                    SaltBytes = salt;
                }
                else
                {
                    Random r = new Random();
                    int SaltLenght = r.Next(minSaltLength, maxSaltLenght);
                    SaltBytes = new byte[SaltLenght];
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                    rng.GetNonZeroBytes(SaltBytes);
                    rng.Dispose();
                }

                byte[] plaintData = ASCIIEncoding.UTF8.GetBytes(plaintext);
                byte[] plainDataAndSalt = new byte[plaintData.Length + SaltBytes.Length];

                for(int x=0; x<plaintData.Length;x++)
                {
                    plainDataAndSalt[x] = plaintData[x];
                    
                }
                for (int n = 0; n < SaltBytes.Length; n++)
                    plainDataAndSalt[plaintData.Length + n] = SaltBytes[n];

                byte[] hashValue = null;

                switch(hash)
                {
                    case Supported_HA.SHA256:
                        SHA256Managed sha= new SHA256Managed();
                        hashValue= sha.ComputeHash(plainDataAndSalt);
                        sha.Dispose();
                        break;

                    case Supported_HA.SHA384:
                        SHA384Managed sha1 = new SHA384Managed();
                        hashValue = sha1.ComputeHash(plainDataAndSalt);
                        sha1.Dispose();
                        break;
                    case Supported_HA.SHA512:
                        SHA512Managed sha2 = new SHA512Managed();
                        hashValue = sha2.ComputeHash(plainDataAndSalt);
                        sha2.Dispose();
                        break;
                }

                byte[] resuflt = new byte[hashValue.Length + SaltBytes.Length];
                for (int x = 0; x < hashValue.Length; x++)
                    resuflt[x] = hashValue[x];
                for (int n = 0; n < SaltBytes.Length; n++)
                    resuflt[hashValue.Length + n] = SaltBytes[n];
                return Convert.ToBase64String(resuflt);
            }
        /// <summary>
        /// Generates a random key
        /// </summary>
        /// <param name="numberOfBytes">
        /// length of the key in bytes
        /// </param>
        /// <returns>
        /// The create key.
        /// </returns>
        public static string CreateKey(int numberOfBytes)
        {
            if (numberOfBytes < 1)
            {
                throw new ArgumentOutOfRangeException("numberOfBytes");
            }

            RNGCryptoServiceProvider rng = null;

            try
            {
                rng = new RNGCryptoServiceProvider();
                var buff = new byte[numberOfBytes];

                rng.GetBytes(buff);
                return buff.BytesToHexString();
            }
            finally
            {
                if (rng != null)
                {
                    rng.Dispose();
                }
            }
        }
Beispiel #7
0
        bool testRng(Session session)
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(session);

            byte[] data1 = new byte[1024];
            byte[] data2 = new byte[1024];
            byte[] data3 = new byte[1024];

            rng.GetBytes(data1);
            rng.GetBytes(data2);
            rng.Dispose();

            rng = new RNGCryptoServiceProvider(session);

            rng.GetBytes(data3);
            rng.Dispose();

            int same = 0;
            for (int i = 0; i < data1.Length; i++)
            {
                if (data1[i] == data2[i] || data1[i] == data3[i] || data2[i] == data3[i]) same++;
            }

            return same < 32; // ~3% matching elements
        }
Beispiel #8
0
        private string GetSalt()
        {
            RNGCryptoServiceProvider saltGen = null;
            string salt = string.Empty;

            try
            {
                saltGen = new RNGCryptoServiceProvider();
                byte[] buffer = new byte[Constants.SALT_SIZE];
                saltGen.GetBytes(buffer);
                salt = Convert.ToBase64String(buffer);
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (saltGen != null)
                {
                    saltGen.Dispose();
                    saltGen = null;
                }
            }

            return salt;
        }
 public static int GetRandomSeed()
 {
     byte[] bytes = new byte[4];
     System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
     rng.GetBytes(bytes);
     rng.Dispose();
     return(BitConverter.ToInt32(bytes, 0));
 }
Beispiel #10
0
        private int[] ランダムな突然変異(int[] original, int[,] パラメータ)
        {
            int パラメータ数 = パラメータ.Length / 2;

            //Int32と同じサイズのバイト配列にランダムな値を設定する
            //byte[] bs = new byte[sizeof(int)];
            byte[] bs = new byte[4];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetBytes(bs);
            //Int32に変換する
            int seed = System.BitConverter.ToInt32(bs, 0);
            // そのseedを基にRandomを作る
            var r = new Random(seed++);

            int 数 = r.Next(パラメータ数) + 1;

            int[] gene = new int[パラメータ数 + 他の要素];
            //重複しないように変更するパラメータを選ぶ
            HashSet <int> 更するパラメータ = new HashSet <int>();

            while (更するパラメータ.Count < 数)
            {
                更するパラメータ.Add(r.Next(パラメータ数));
            }

            if (パラメータ[0, 0] == 0)//スキップするとき
            {
                数 = r.Next(パラメータ数 - 2) + 1;
                更するパラメータ.Clear();
                while (更するパラメータ.Count < 数)
                {
                    更するパラメータ.Add(r.Next(2, パラメータ数));
                }
            }

            for (int j = 0; j < パラメータ数; j++)
            {
                if (更するパラメータ.Contains(j))
                {
                    //System.Diagnostics.Debug.Write(j + ",");
                    gene[j] = r.Next(パラメータ[j, 0], パラメータ[j, 1] + 1);
                }
                else
                {
                    gene[j] = original[j];
                }
            }
            更するパラメータ = null;
            bs       = null;
            rng.Dispose();
            r = null;
            return(gene);
        }
Beispiel #11
0
        /// <summary>
        /// Creates a salted PBKDF2 hash of the password.
        /// </summary>
        /// <param name="password">The password to hash.</param>
        /// <returns>The hash of the password.</returns>
        public static string CreateHash(string password)
        {
            // Generate a random salt
            RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
            byte[] salt = new byte[SALT_BYTE_SIZE];
            csprng.GetBytes(salt);

            // Hash the password and encode the parameters
            byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
            csprng.Dispose();
            return PBKDF2_ITERATIONS + ":" +
                Convert.ToBase64String(salt) + ":" +
                Convert.ToBase64String(hash);
        }
Beispiel #12
0
        static public void setup()
        {
            System.Security.Cryptography.RNGCryptoServiceProvider rng;
            rng = new System.Security.Cryptography.RNGCryptoServiceProvider();

            byte[] randSeed = new byte[4];
            rng.GetBytes(randSeed);

            rng.Dispose();

            PRNG.seed = 0;
            foreach (byte b in randSeed)
            {
                PRNG.seed = (PRNG.seed << 8) | (0xff & (uint)b);
            }
        }
        public static int GenerateRandomNumber()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Buffer storage.
            byte[] data = new byte[4];


            // Fill buffer.
            rng.GetBytes(data);

            // Convert to int 32.
            int value = BitConverter.ToInt32(data, 0);
            rng.Dispose();

            return value;
        }
Beispiel #14
0
 /// <summary>
 /// 產生指定大小的隨機byte數據檔案
 /// </summary>
 /// <param name="randomCount">byte數量</param>
 public static void WriteFile(int randomCount,string fileName)
 {
     RandomNumberGenerator ranObj = new RNGCryptoServiceProvider();
     byte[] randomData = new byte[randomCount];
     string filePath = AppDomain.CurrentDomain.BaseDirectory + @"\" + fileName;
     // 1. Byte Array產生Random數據
     ranObj.GetBytes(randomData);
     ranObj.Dispose();
     // 2. 寫入字串並稍為改寫字串表達意義
     StringBuilder ranStr = new StringBuilder();
     foreach (byte b in randomData)
     {
         ranStr.Append(String.Format("0x{0:X2}, ", b));
     }
     // 3. 寫入檔案流中
     using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
     {
         using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
         {
             sw.Write(ranStr.ToString(0, ranStr.Length - 2));//多兩個字串 => ", " 所以扣2
             sw.Flush();
         }
     }
 }
Beispiel #15
0
        private void StartExpandingToMainForm(bool instant = false)
        {
            if (checkBoxSaveSettings.Checked)
            {
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] buffer = new byte[1024];
                rng.GetBytes(buffer);
                string salt = BitConverter.ToString(buffer);
                rng.Dispose();

                Settings.Default.Entropy = salt;
                Settings.Default.Host = textBoxHost.Text;
                Settings.Default.User = textBoxUsername.Text;
                Settings.Default.Password = textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                Settings.Default.Database = textBoxWorldDatabase.Text;
                Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;
                Settings.Default.Port = XConverter.ToUInt32(textBoxPort.Text);
                Settings.Default.Save();
            }

            ResetFieldsToDefault();
            Text = "SAI-Editor - Connection: " + textBoxUsername.Text + ", " + textBoxHost.Text + ", " + textBoxPort.Text;

            if (instant)
            {
                Width = WidthToExpandTo;
                Height = HeightToExpandTo;
                formState = FormState.FormStateMain;

                if (Settings.Default.ShowTooltipsPermanently)
                    ExpandToShowPermanentTooltips(false);
            }
            else
            {
                formState = FormState.FormStateExpandingOrContracting;
                timerExpandOrContract.Enabled = true;
                expandingToMainForm = true;
            }

            foreach (Control control in controlsLoginForm)
                control.Visible = false;

            foreach (Control control in controlsMainForm)
                control.Visible = instant;

            panelPermanentTooltipTypes.Visible = false;
            panelPermanentTooltipParameters.Visible = false;

            //TestForm tf = new TestForm();
            //tf.Show();
        }
	public static bool nativeGenerateSeed(byte[] result)
	{
		try
		{
			RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
			csp.GetBytes(result);
#if NET_4_0
			csp.Dispose();
#endif
			return true;
		}
		catch (CryptographicException)
		{
			return false;
		}
	}
Beispiel #17
0
        private void SaveLastUsedFields()
        {
            Settings.Default.ShowBasicInfo = GetActiveUserControl().checkBoxShowBasicInfo.Checked;
            Settings.Default.LockSmartScriptId = GetActiveUserControl().checkBoxLockEventId.Checked;
            Settings.Default.ListActionLists = GetActiveUserControl().checkBoxListActionlistsOrEntries.Checked;
            Settings.Default.AllowChangingEntryAndSourceType = GetActiveUserControl().checkBoxAllowChangingEntryAndSourceType.Checked;
            Settings.Default.PhaseHighlighting = GetActiveUserControl().checkBoxUsePhaseColors.Checked;
            Settings.Default.ShowTooltipsStaticly = GetActiveUserControl().checkBoxUseStaticTooltips.Checked;

            string lastStaticInfoPerTab = String.Empty;

            //entryorguid,sourceTypeIndex,entryorguid,sourceTypeIndex,entryorguid,sourceTypeIndex,....
            foreach (UserControlSAI uc in userControls)
                lastStaticInfoPerTab += uc.textBoxEntryOrGuid.Text + "-" + uc.comboBoxSourceType.SelectedIndex + ",";

            Settings.Default.LastStaticInfoPerTab = lastStaticInfoPerTab;

            if (formState == FormState.FormStateLogin)
            {
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] buffer = new byte[1024];
                rng.GetBytes(buffer);
                string salt = BitConverter.ToString(buffer);
                rng.Dispose();

                Settings.Default.Entropy = salt;
                Settings.Default.Host = textBoxHost.Text;
                Settings.Default.User = textBoxUsername.Text;
                Settings.Default.Password = textBoxPassword.Text.Length == 0 ? String.Empty : textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                Settings.Default.Database = textBoxWorldDatabase.Text;
                Settings.Default.Port = CustomConverter.ToUInt32(textBoxPort.Text);
                Settings.Default.UseWorldDatabase = radioButtonConnectToMySql.Checked;
                Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;
            }

            Settings.Default.Save();
        }
Beispiel #18
0
        public static EnumUserCreationResult criarUsuario(Usuario novousuario)
        {
            /*
        id_usuario
        apelido
        email
        password
        salt
        celular
        */
            SqlDataReader dr = null;
            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlTransaction trans = null;
            RNGCryptoServiceProvider rnd;            
            String strSql = "SELECT id_usuario from Usuario where email='" + novousuario.Email + "'";

            try
            {
                conn = new SqlConnection(ConnString);
                conn.Open();
                cmd = conn.CreateCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                cmd.CommandText = strSql;
                trans = conn.BeginTransaction();
                cmd.Transaction = trans;
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    dr.Close();
                    trans.Rollback();
                    return EnumUserCreationResult.EMAIL_JA_EXISTENTE;
                }

                dr.Close();
                strSql = "SELECT id_usuario from Usuario where apelido='" + novousuario.Apelido + "'";
                cmd.CommandText = strSql;
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    dr.Close();
                    trans.Rollback();
                    return EnumUserCreationResult.APELIDO_JA_EXISTENTE;
                }
                dr.Close();

                strSql = "INSERT into Usuario(apelido, email, celular, password, salt, token) output Inserted.id_usuario VALUES ('";
                strSql += Utils.limpaString(novousuario.Apelido) + "','" + Utils.limpaString(novousuario.Email) + "','";
                strSql += Utils.limpaString(novousuario.Celular) + "'"; // +"',convert(binary(20),'";

                rnd = new RNGCryptoServiceProvider();
                byte[] salt = new byte[20];
                rnd.GetBytes(salt);
                rnd.Dispose();

                String strSalt = byteArray2String(salt);

                //strSql += GetSHA1HashData(strSalt + novousuario.Password) + "'), convert(binary(20),'" + strSalt + "'),'";
                //strSql += GetSHA1HashData(novousuario.Password) + "'), convert(binary(20),'" + strSalt + "'),'";

                strSql += ",'" + GetSHA1HashData(strSalt + novousuario.Password) + "'";
                strSql += ",'" + strSalt + "'";
                novousuario.Token = Guid.NewGuid();
                strSql += ",'" + novousuario.Token.ToString() + "')";

                cmd.CommandText = strSql;
                dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    novousuario.IdUsuario = System.Convert.ToInt32(dr["id_usuario"]);
                }
                dr.Close();
                trans.Commit();
                return EnumUserCreationResult.SUCCESS;
            }
            catch
            {
                if (dr != null) dr.Close();
                trans.Rollback();
                return EnumUserCreationResult.UNKNOWN_ERROR;
            }
            finally
            {
                if (dr != null) dr.Close();
                if (conn != null) conn.Close();
            }
        }//criarUsuario()
Beispiel #19
0
        private void SaveSettings()
        {
            if (checkBoxChangeStaticInfo.Checked != Settings.Default.ChangeStaticInfo)
            {
                EntryOrGuidAndSourceType originalEntryOrGuidAndSourceType = ((MainForm)Owner).GetActiveUserControl().originalEntryOrGuidAndSourceType;
                ((MainForm)Owner).GetActiveUserControl().textBoxEntryOrGuid.Text = originalEntryOrGuidAndSourceType.entryOrGuid.ToString();
                ((MainForm)Owner).GetActiveUserControl().comboBoxSourceType.SelectedIndex = ((MainForm)Owner).GetActiveUserControl().GetIndexBySourceType(originalEntryOrGuidAndSourceType.sourceType);
            }

            bool showTooltipsStaticly = Settings.Default.ShowTooltipsStaticly;
            bool generateComments = Settings.Default.GenerateComments;
            bool phaseHighlighting = Settings.Default.PhaseHighlighting;

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buffer = new byte[1024];

            rng.GetBytes(buffer);
            string salt = BitConverter.ToString(buffer);

            rng.Dispose();
            string decryptedPassword = textBoxPassword.Text;

            SAI_Editor_Manager.Instance.connString = new MySqlConnectionStringBuilder();
            SAI_Editor_Manager.Instance.connString.Server = textBoxHost.Text;
            SAI_Editor_Manager.Instance.connString.UserID = textBoxUsername.Text;
            SAI_Editor_Manager.Instance.connString.Port = CustomConverter.ToUInt32(textBoxPort.Text);
            SAI_Editor_Manager.Instance.connString.Database = textBoxWorldDatabase.Text;

            if (textBoxPassword.Text.Length > 0)
                SAI_Editor_Manager.Instance.connString.Password = textBoxPassword.Text;

            Settings.Default.UseWorldDatabase = radioButtonConnectToMySql.Checked;
            Settings.Default.Save();

            bool newConnectionSuccesfull = false;
            
            if (radioButtonConnectToMySql.Checked)
                newConnectionSuccesfull = SAI_Editor_Manager.Instance.worldDatabase.CanConnectToDatabase(SAI_Editor_Manager.Instance.connString, false);

            //! We also save the settings if no connection was made. It's possible the user unchecked
            //! the radioboxes, changed some settings and then set it back to no DB connection.
            if (newConnectionSuccesfull || !radioButtonConnectToMySql.Checked)
            {
                Settings.Default.Entropy = salt;
                Settings.Default.Host = textBoxHost.Text;
                Settings.Default.User = textBoxUsername.Text;
                Settings.Default.Password = textBoxPassword.Text.Length == 0 ? String.Empty : textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                Settings.Default.Database = textBoxWorldDatabase.Text;
                Settings.Default.Port = textBoxPort.Text.Length > 0 ? CustomConverter.ToUInt32(textBoxPort.Text) : 0;
                Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;

                if (radioButtonConnectToMySql.Checked)
                    SAI_Editor_Manager.Instance.ResetDatabases();
            }

            Settings.Default.InstantExpand = checkBoxInstantExpand.Checked;
            Settings.Default.PromptToQuit = checkBoxPromptToQuit.Checked;
            Settings.Default.HidePass = checkBoxHidePass.Checked;
            Settings.Default.AnimationSpeed = CustomConverter.ToInt32(textBoxAnimationSpeed.Text);
            Settings.Default.PromptExecuteQuery = checkBoxPromptExecuteQuery.Checked;
            Settings.Default.ChangeStaticInfo = checkBoxChangeStaticInfo.Checked;
            Settings.Default.ShowTooltipsStaticly = checkBoxShowTooltipsStaticly.Checked;
            Settings.Default.GenerateComments = checkBoxAutoGenerateComments.Checked;
            Settings.Default.CreateRevertQuery = checkBoxCreateRevertQuery.Checked;
            Settings.Default.PhaseHighlighting = checkBoxPhaseHighlighting.Checked;
            Settings.Default.DuplicatePrimaryFields = checkBoxDuplicatePrimaryFields.Checked;
            Settings.Default.WowExpansionIndex = (uint)comboBoxWowExpansion.SelectedIndex;
            SAI_Editor_Manager.Instance.Expansion = (WowExpansion)Settings.Default.WowExpansionIndex;
            Settings.Default.Save();

            if (newConnectionSuccesfull)
            {
                ((MainForm)Owner).checkBoxAutoConnect.Checked = checkBoxAutoConnect.Checked;
                ((MainForm)Owner).textBoxHost.Text = textBoxHost.Text;
                ((MainForm)Owner).textBoxUsername.Text = textBoxUsername.Text;
                ((MainForm)Owner).textBoxPassword.Text = decryptedPassword;
                ((MainForm)Owner).textBoxWorldDatabase.Text = textBoxWorldDatabase.Text;
                ((MainForm)Owner).checkBoxAutoConnect.Checked = checkBoxAutoConnect.Checked;
                ((MainForm)Owner).expandAndContractSpeed = CustomConverter.ToInt32(textBoxAnimationSpeed.Text);
                ((MainForm)Owner).textBoxPassword.PasswordChar = Convert.ToChar(checkBoxHidePass.Checked ? '●' : '\0');
            }
            else if (radioButtonConnectToMySql.Checked) //! Don't report this if there is no connection to be made anyway
                MessageBox.Show("The database settings were not saved because no connection could be established. All other changed settings were saved.", "Something went wrong!", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (checkBoxAutoGenerateComments.Checked != generateComments && checkBoxAutoGenerateComments.Checked)
                ((MainForm)Owner).GetActiveUserControl().GenerateCommentsForAllItems();
            
            if (checkBoxShowTooltipsStaticly.Checked != showTooltipsStaticly)
                ((MainForm)Owner).GetActiveUserControl().ExpandOrContractToShowStaticTooltips(!checkBoxShowTooltipsStaticly.Checked);

            if (checkBoxPhaseHighlighting.Checked != phaseHighlighting)
            {
                ((MainForm)Owner).GetActiveUserControl().listViewSmartScripts.Init(true);
                ((MainForm)Owner).GetActiveUserControl().checkBoxUsePhaseColors.Checked = checkBoxPhaseHighlighting.Checked;
            }

            ((MainForm)Owner).HandleUseWorldDatabaseSettingChanged();
        }
Beispiel #20
0
        /// <summary>
        /// Generates a random password.
        /// </summary>
        /// <param name="minLength">
        /// Minimum password length.
        /// </param>
        /// <param name="maxLength">
        /// Maximum password length.
        /// </param>
        /// <returns>
        /// Randomly generated password.
        /// </returns>
        /// <remarks>
        /// The length of the generated password will be determined at
        /// random and it will fall with the range determined by the
        /// function parameters.
        /// </remarks>
        public static string Generate(int minLength,
                                      int maxLength)
        {
            // Make sure that input parameters are valid.
            if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
                return null;

            // Create a local array containing supported password characters
            // grouped by types. You can remove character groups from this
            // array, but doing so will weaken the password strength.
            char[][] charGroups = new char[][]
                {
                PASSWORD_CHARS_LCASE.ToCharArray(),
                PASSWORD_CHARS_UCASE.ToCharArray(),
                PASSWORD_CHARS_NUMERIC.ToCharArray(),
                PASSWORD_CHARS_SPECIAL.ToCharArray()
                };

            // Use this array to track the number of unused characters in each
            // character group.
            int[] charsLeftInGroup = new int[charGroups.Length];

            // Initially, all characters in each group are not used.
            for (int i = 0; i < charsLeftInGroup.Length; i++)
                charsLeftInGroup[i] = charGroups[i].Length;

            // Use this array to track (iterate through) unused character groups.
            int[] leftGroupsOrder = new int[charGroups.Length];

            // Initially, all character groups are not used.
            for (int i = 0; i < leftGroupsOrder.Length; i++)
                leftGroupsOrder[i] = i;

            // Use a 4-byte array to fill it with random bytes and convert it then
            // to an integer value.
            byte[] randomBytes = new byte[4];

            // Generate 4 random bytes.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(randomBytes);

            // Convert 4 bytes into a 32-bit integer value.
            int seed = BitConverter.ToInt32(randomBytes, 0);

            // Now, this is real randomization.
            Random random = new Random(seed);

            // This array will hold password characters.
            char[] password = null;

            // Allocate appropriate memory for the password.
            if (minLength < maxLength)
                password = new char[random.Next(minLength, maxLength + 1)];
            else
                password = new char[minLength];

            // Index of the next character to be added to password.
            int nextCharIdx;

            // Index of the next character group to be processed.
            int nextGroupIdx;

            // Index which will be used to track not processed character groups.
            int nextLeftGroupsOrderIdx;

            // Index of the last non-processed character in a group.
            int lastCharIdx;

            // Index of the last non-processed group.
            int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

            // Generate password characters one at a time.
            for (int i = 0; i < password.Length; i++)
            {
                // If only one character group remained unprocessed, process it;
                // otherwise, pick a random character group from the unprocessed
                // group list. To allow a special character to appear in the
                // first position, increment the second parameter of the Next
                // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
                if (lastLeftGroupsOrderIdx == 0)
                    nextLeftGroupsOrderIdx = 0;
                else
                    nextLeftGroupsOrderIdx = random.Next(0,
                                                         lastLeftGroupsOrderIdx);

                // Get the actual index of the character group, from which we will
                // pick the next character.
                nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

                // Get the index of the last unprocessed characters in this group.
                lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

                // If only one unprocessed character is left, pick it; otherwise,
                // get a random character from the unused character list.
                if (lastCharIdx == 0)
                    nextCharIdx = 0;
                else
                    nextCharIdx = random.Next(0, lastCharIdx + 1);

                // Add this character to the password.
                password[i] = charGroups[nextGroupIdx][nextCharIdx];

                // If we processed the last character in this group, start over.
                if (lastCharIdx == 0)
                    charsLeftInGroup[nextGroupIdx] =
                                              charGroups[nextGroupIdx].Length;
                // There are more unprocessed characters left.
                else
                {
                    // Swap processed character with the last unprocessed character
                    // so that we don't pick it until we process all characters in
                    // this group.
                    if (lastCharIdx != nextCharIdx)
                    {
                        char temp = charGroups[nextGroupIdx][lastCharIdx];
                        charGroups[nextGroupIdx][lastCharIdx] =
                                    charGroups[nextGroupIdx][nextCharIdx];
                        charGroups[nextGroupIdx][nextCharIdx] = temp;
                    }
                    // Decrement the number of unprocessed characters in
                    // this group.
                    charsLeftInGroup[nextGroupIdx]--;
                }

                // If we processed the last group, start all over.
                if (lastLeftGroupsOrderIdx == 0)
                    lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
                // There are more unprocessed groups left.
                else
                {
                    // Swap processed group with the last unprocessed group
                    // so that we don't pick it until we process all groups.
                    if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                    {
                        int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                        leftGroupsOrder[lastLeftGroupsOrderIdx] =
                                    leftGroupsOrder[nextLeftGroupsOrderIdx];
                        leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                    }
                    // Decrement the number of unprocessed groups.
                    lastLeftGroupsOrderIdx--;
                }
            }

            // Convert password characters into a string and return the result.
            rng.Dispose();
            return new string(password);
        }
Beispiel #21
0
        private void SaveLastUsedFields()
        {
            Settings.Default.LastEntryOrGuid = textBoxEntryOrGuid.Text;
            Settings.Default.LastSourceType = comboBoxSourceType.SelectedIndex;
            Settings.Default.ShowBasicInfo = checkBoxShowBasicInfo.Checked;
            Settings.Default.LockSmartScriptId = checkBoxLockEventId.Checked;
            Settings.Default.ListActionLists = checkBoxListActionlistsOrEntries.Checked;
            Settings.Default.AllowChangingEntryAndSourceType = checkBoxAllowChangingEntryAndSourceType.Checked;
            Settings.Default.PhaseHighlighting = checkBoxUsePhaseColors.Checked;
            Settings.Default.ShowTooltipsPermanently = checkBoxUsePermanentTooltips.Checked;

            if (formState == FormState.FormStateLogin)
            {
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] buffer = new byte[1024];
                rng.GetBytes(buffer);
                string salt = BitConverter.ToString(buffer);
                rng.Dispose();

                Settings.Default.Entropy = salt;
                Settings.Default.Host = textBoxHost.Text;
                Settings.Default.User = textBoxUsername.Text;
                Settings.Default.Password = textBoxPassword.Text.Length == 0 ? String.Empty : textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                Settings.Default.Database = textBoxWorldDatabase.Text;
                Settings.Default.Port = XConverter.ToUInt32(textBoxPort.Text);
                Settings.Default.UseWorldDatabase = radioButtonConnectToMySql.Checked;
                Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;
            }

            Settings.Default.Save();
        }
        private void FinishButtonPressed(CancelRoutedEventArgs e)
        {

            var settings = Settings.Default;

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buffer = new byte[1024];

            rng.GetBytes(buffer);
            string salt = BitConverter.ToString(buffer);

            rng.Dispose();

            settings.Entropy = salt;

            settings.DBHost = MySQLHost;
            settings.DBPort = MySQLPort;
            settings.DBUsername = MySQLUsername;
            settings.DBPassword = MySQLPassword.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));

            settings.DBAuthName = SelectedAuthDB;
            settings.DBCharName = SelectedCharDB;
            settings.DBWorldName = SelectedWorldDB;

            if (ConnectLocally)
            {
                settings.ServerType = (int)ServerType.Local;
                settings.ServerFolder = ServerFolderLocation;
            }
            else
            {
                settings.ServerType = (int)ServerType.RemoteAccess;
                settings.RAUsername = Username;
                settings.RAPassword = Password.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                settings.RAHost = Host;
                settings.RAPort = Port;
            }

            settings.Save();
            SaveAndCloseViewModel();
        }
Beispiel #23
0
        private void SaveSettings()
        {
            if (checkBoxChangeStaticInfo.Checked != Settings.Default.ChangeStaticInfo)
            {
                EntryOrGuidAndSourceType originalEntryOrGuidAndSourceType = ((MainForm)Owner).originalEntryOrGuidAndSourceType;
                ((MainForm)Owner).textBoxEntryOrGuid.Text = originalEntryOrGuidAndSourceType.entryOrGuid.ToString();
                ((MainForm)Owner).comboBoxSourceType.SelectedIndex = ((MainForm)Owner).GetIndexBySourceType(originalEntryOrGuidAndSourceType.sourceType);
            }

            bool showTooltipsPermanently = Settings.Default.ShowTooltipsPermanently;
            bool generateComments = Settings.Default.GenerateComments;
            bool phaseHighlighting = Settings.Default.PhaseHighlighting;

            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buffer = new byte[1024];

            rng.GetBytes(buffer);
            string salt = BitConverter.ToString(buffer);

            rng.Dispose();
            string decryptedPassword = textBoxPassword.Text;

            connectionString.Server = textBoxHost.Text;
            connectionString.UserID = textBoxUsername.Text;
            connectionString.Port = XConverter.ToUInt32(textBoxPort.Text);
            connectionString.Database = textBoxWorldDatabase.Text;

            if (textBoxPassword.Text.Length > 0)
                connectionString.Password = textBoxPassword.Text;

            bool newConnectionSuccesfull = SAI_Editor_Manager.Instance.worldDatabase.CanConnectToDatabase(connectionString, false);

            if (newConnectionSuccesfull)
            {
                Settings.Default.Entropy = salt;
                Settings.Default.Host = textBoxHost.Text;
                Settings.Default.User = textBoxUsername.Text;
                Settings.Default.Password = decryptedPassword.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                Settings.Default.Database = textBoxWorldDatabase.Text;
                Settings.Default.Port = textBoxPort.Text.Length > 0 ? XConverter.ToUInt32(textBoxPort.Text) : 0;
                Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;
                ((MainForm)Owner).connectionString = connectionString;
                SAI_Editor_Manager.Instance.ResetDatabases();
            }

            Settings.Default.InstantExpand = checkBoxInstantExpand.Checked;
            Settings.Default.LoadScriptInstantly = checkBoxLoadScriptInstantly.Checked;
            Settings.Default.AutoSaveSettings = checkBoxAutoSaveSettings.Checked;
            Settings.Default.PromptToQuit = checkBoxPromptToQuit.Checked;
            Settings.Default.HidePass = checkBoxHidePass.Checked;
            Settings.Default.AnimationSpeed = XConverter.ToInt32(textBoxAnimationSpeed.Text);
            Settings.Default.PromptExecuteQuery = checkBoxPromptExecuteQuery.Checked;
            Settings.Default.ChangeStaticInfo = checkBoxChangeStaticInfo.Checked;
            Settings.Default.ShowTooltipsPermanently = checkBoxShowTooltipsPermanently.Checked;
            Settings.Default.GenerateComments = checkBoxAutoGenerateComments.Checked;
            Settings.Default.CreateRevertQuery = checkBoxCreateRevertQuery.Checked;
            Settings.Default.PhaseHighlighting = checkBoxPhaseHighlighting.Checked;
            Settings.Default.Save();

            if (newConnectionSuccesfull)
            {
                ((MainForm)Owner).checkBoxAutoConnect.Checked = checkBoxAutoConnect.Checked;
                ((MainForm)Owner).textBoxHost.Text = textBoxHost.Text;
                ((MainForm)Owner).textBoxUsername.Text = textBoxUsername.Text;
                ((MainForm)Owner).textBoxPassword.Text = decryptedPassword;
                ((MainForm)Owner).textBoxWorldDatabase.Text = textBoxWorldDatabase.Text;
                ((MainForm)Owner).checkBoxAutoConnect.Checked = checkBoxAutoConnect.Checked;
                ((MainForm)Owner).expandAndContractSpeed = XConverter.ToInt32(textBoxAnimationSpeed.Text);
                ((MainForm)Owner).textBoxPassword.PasswordChar = Convert.ToChar(checkBoxHidePass.Checked ? '●' : '\0');
            }
            else
                MessageBox.Show("The database settings were not saved because no connection could be established.", "Something went wrong!", MessageBoxButtons.OK, MessageBoxIcon.Error);

            if (checkBoxAutoGenerateComments.Checked != generateComments && checkBoxAutoGenerateComments.Checked)
                ((MainForm)Owner).GenerateCommentsForAllItems();
            
            if (checkBoxShowTooltipsPermanently.Checked != showTooltipsPermanently)
                ((MainForm)Owner).ExpandToShowPermanentTooltips(!checkBoxShowTooltipsPermanently.Checked);

            if (checkBoxPhaseHighlighting.Checked != phaseHighlighting)
                ((MainForm)Owner).listViewSmartScripts.Init();
        }
        /// <summary>
        /// Simple test.
        /// </summary>
        /// <param name="wordSize">number of byte of the key</param>
        /// <param name="testPrecision">percision of the test, error = 1/2^precision</param>
        /// <returns>result of the test</returns>
        public static bool DefaultTest(uint wordSize=128, uint testPrecision=20)
        {
            if (wordSize < 8 || testPrecision < 1)
            {
                System.Console.WriteLine("FiatShamirIdentification test invalid input\n");
                return false;
            }

            uint iteration = 0;
            bool choice;
            BigInteger number;
            bool result = true;
            var generator = new RNGCryptoServiceProvider();
            var priv = PrivateKey.NewKey(generator, wordSize);
            var pub = priv.GetPublicKey();
            Verifier verifier = pub.GetVerifier();
            Proover proover = priv.GetProover(generator);

            //test with key
            while (iteration < testPrecision && result)
            {
                number = proover.Step1();
                choice = verifier.Step1(ref number);
                number = proover.Step2(choice);
                verifier.Step2(number);
                result = verifier.CheckState();
                iteration++;
            }

            if (!result) //if not verified, fail
            {
                System.Console.WriteLine("FiatShamirIdentification test ERROR\n");
                generator.Dispose();
                return false;
            }


            //test without key
            var genwrap = new GeneratorWrap(generator, wordSize);
            var falseKey = new PrivateKey(genwrap.GetBig(), genwrap.GetBig(), wordSize);
            proover = new Proover(falseKey, generator);
            iteration = 0;
            while (iteration < testPrecision && result)
            {
                number = proover.Step1();
                choice = verifier.Step1(ref number);
                number = proover.Step2(choice);
                verifier.Step2(number);
                result = verifier.CheckState();
                iteration++;
            }

            if (result) //if verified, fail
            {
                System.Console.WriteLine("FiatShamirIdentification test ERROR\n");
                generator.Dispose();
                return false;
            }

            System.Console.WriteLine("FiatShamirIdentification test OK\n");
            generator.Dispose();
            return true;
        }
Beispiel #25
0
        private int[,] 次の局所集団を作成(Mat[] テンプレート, Mat[] 合成用素材, Mat[] 合成画像, int[][,] 正解座標, int[,] group, int[,] パラメータ)
        {
            int パラメータ数 = パラメータ.Length / 2;

            int[,] next_group = new int[4, パラメータ数 + 他の要素];



            if (group[0, 0] + group[0, 1] + group[0, 2] + group[0, 3] + group[0, 4] == 0)
            {
                next_group = 局所集団の初期化(テンプレート, 合成用素材, 合成画像, 正解座標, パラメータ);
                Console.WriteLine("パラメータ初期化");
            }
            else//初期状態じゃなかったら
            {//子供優先の順位付け
                var 家族 = new Dictionary <string, int>();

                int[] 親の大きい方 = new int[パラメータ数 + 他の要素];
                int[] 親の小さい方 = new int[パラメータ数 + 他の要素];
                int[] 子の大きい方 = new int[パラメータ数 + 他の要素];
                int[] 子の小さい方 = new int[パラメータ数 + 他の要素];
                int[] 新子供1   = new int[パラメータ数 + 他の要素];
                int[] 新子供2   = new int[パラメータ数 + 他の要素];

                //順位を格納
                int PA = 0;
                int PZ = 0;
                int CA = 0;
                int CZ = 0;


                //親子の点数の関係を確認
                if (group[0, パラメータ数] > group[1, パラメータ数])
                {
                    for (int i = 0; i < パラメータ数 + 他の要素; i++)
                    {
                        親の大きい方[i] = group[0, i];
                        親の小さい方[i] = group[1, i];
                    }
                }
                else
                {
                    for (int i = 0; i < パラメータ数 + 3; i++)
                    {
                        親の大きい方[i] = group[1, i];
                        親の小さい方[i] = group[0, i];
                    }
                }
                if (group[2, パラメータ数] > group[3, パラメータ数])
                {
                    for (int i = 0; i < パラメータ数 + 他の要素; i++)
                    {
                        子の大きい方[i] = group[2, i];
                        子の小さい方[i] = group[3, i];
                    }
                }
                else
                {
                    for (int i = 0; i < パラメータ数 + 他の要素; i++)
                    {
                        子の大きい方[i] = group[3, i];
                        子の小さい方[i] = group[2, i];
                    }
                }

                家族.Add("PA", 親の大きい方[パラメータ数]);
                家族.Add("PZ", 親の小さい方[パラメータ数]);
                家族.Add("CA", 子の大きい方[パラメータ数]);
                家族.Add("CZ", 子の小さい方[パラメータ数]);
                var sorted = 家族.OrderByDescending(x => x.Value).ThenBy(x => x.Key);

                int 順位 = 1;
                foreach (var 体 in sorted)
                {
                    if (体.Key.Equals("PA"))
                    {
                        PA = 順位;
                    }
                    else if (体.Key.Equals("PZ"))
                    {
                        PZ = 順位;
                    }
                    else if (体.Key.Equals("CA"))
                    {
                        CA = 順位;
                    }
                    else if (体.Key.Equals("CZ"))
                    {
                        CZ = 順位;
                    }

                    //Console.WriteLine("{0}:{1}:{2}", 個体.Key, 個体.Value, 順位);

                    順位++;
                }


                //子2個体がともに親の2個体より良かった場合(ケースA)は、子2個体及び適応度の良かった方の親個体計3個体が局所集団に戻し,そのうち二体を親として選ぶ。
                if (CZ < PA)//小さいほうが順位が高い
                {
                    //System.Diagnostics.Debug.WriteLine("Pattern A");
                    //Int32と同じサイズのバイト配列にランダムな値を設定する
                    //byte[] bs = new byte[sizeof(int)];
                    byte[] bs = new byte[4];
                    System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
                    rng.GetBytes(bs);
                    //Int32に変換する
                    int seed = System.BitConverter.ToInt32(bs, 0);
                    // そのseedを基にRandomを作る
                    var r      = new Random(seed++);
                    int number = r.Next(3);

                    //親2体が全く同じパラメータになるのを回避
                    if (子の大きい方.SequenceEqual(子の小さい方) && 子の小さい方.SequenceEqual(親の大きい方))
                    {
                        next_group = 親から次の家族を作成(子の大きい方, ランダムに遺伝子1つ作成(パラメータ), パラメータ);
                    }
                    else
                    {
                        while (true)
                        {
                            //局所集団から2個体(親)をランダムに取り出し、ランダムな多点交叉を行なう
                            if (number == 2)
                            {
                                if (!子の大きい方.SequenceEqual(子の小さい方))
                                {
                                    next_group = 親から次の家族を作成(子の大きい方, 子の小さい方, パラメータ);
                                    break;
                                }
                                else
                                {
                                    number = 1; //同じだった場合は次のパターンに移る
                                }
                            }
                            else if (number == 1)
                            {
                                if (!子の大きい方.SequenceEqual(親の大きい方))
                                {
                                    next_group = 親から次の家族を作成(子の大きい方, 親の大きい方, パラメータ);
                                    break;
                                }
                                else
                                {
                                    number = 0;
                                }
                            }
                            else if (number == 0)
                            {
                                if (!子の小さい方.SequenceEqual(親の大きい方))
                                {
                                    next_group = 親から次の家族を作成(子の小さい方, 親の大きい方, パラメータ);
                                    break;
                                }
                                else
                                {
                                    number = 2;
                                }
                            }
                        }
                    }
                    bs = null;
                    rng.Dispose();
                    r = null;
                }
                //子2個体がともに親の2個体より悪かった場合(ケースB)は、親2個体のうち良かった方のみが局所集団に戻り、局所集団数は1減少する。
                else if (CA > PZ)
                {
                    //System.Diagnostics.Debug.WriteLine("Pattern B");
                    next_group = 親から次の家族を作成(親の大きい方, ランダムに遺伝子1つ作成(パラメータ), パラメータ);
                }
                //親2個体のうちどちらか一方のみが子2個体より良かった場合(ケースC)は、親2個体のうち良かった方と子2個体のうち良かった方が局所集団に戻り、局所集団数は変化しない。
                else if (PA < CA && PZ > CA)
                {
                    //System.Diagnostics.Debug.WriteLine("Pattern C");
                    next_group = 親から次の家族を作成(親の大きい方, 子の大きい方, パラメータ);
                }
                //子2個体のうちどちらか一方のみが親2個体より良かった場合(ケースD)は、子2個体のうち良かった方のみが局所集団に戻り、全探索空間からランダムに1個体選んで局所集団に追加
                else if (CA < PA && CZ > PA)
                {
                    //System.Diagnostics.Debug.WriteLine("Pattern D");
                    next_group = 親から次の家族を作成(子の大きい方, ランダムに遺伝子1つ作成(パラメータ), パラメータ);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine("newPattern?");
                    next_group = group;
                }

                家族 = null;

                //パラメータから点数を評価
                for (int i = 0; i < 4; i++)
                {
                    int[] buff = 評価結果(テンプレート, 合成用素材, 合成画像, 正解座標, next_group[i, 0], next_group[i, 1], next_group[i, 2], next_group[i, 3], next_group[i, 4]);
                    for (int num = 0; num < 他の要素; num++)
                    {
                        next_group[i, パラメータ数 + num] = buff[num];
                    }
                    //next_group[i, パラメータ数 + 0] = buff[0];
                    //next_group[i, パラメータ数 + 1] = buff[1];
                    //next_group[i, パラメータ数 + 2] = buff[2];
                    // next_group[i, パラメータ数] = 評価結果(テンプレート, 合成用素材, 合成画像, 正解座標, next_group[i, 0], next_group[i, 1], next_group[i, 2], next_group[i, 3], next_group[i, 4]);
                }
            }

            return(next_group);
        }
Beispiel #26
0
        /// <summary>
        /// 生成随机文件名
        /// </summary>
        /// <returns></returns>
        public static string GenerateRandomFileName()
        {
            var key = new byte[10];
            RNGCryptoServiceProvider rng = null;
            try
            {
                rng = new RNGCryptoServiceProvider();
                rng.GetBytes(key);

                char[] rndCharArray = ToBase32StringSuitableForDirName(key).ToCharArray();
                rndCharArray[8] = '.';
                return new String(rndCharArray, 0, 12);
            }
            finally
            {
                if (rng != null)
                    rng.Dispose();
            }
        }
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Settings.Default.RealmlistDir = textBoxRealmlistFile.Text;
            Settings.Default.WorldOfWarcraftDir = textBoxWowFile.Text;
            Settings.Default.LastSelectedIndex = comboBoxRealmlists.SelectedIndex;

            if (!Directory.Exists(xmlDir))
                Directory.CreateDirectory(xmlDir);

            XmlWriterSettings settings = new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 };

            using (XmlWriter writer = XmlWriter.Create(xmlDirFile, settings))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("realms");

                foreach (string realmlist in realmlists.Keys)
                {
                    writer.WriteStartElement("realm");
                    writer.WriteAttributeString("realmlist", realmlist);

                    foreach (KeyValuePair<string, string> accountInfo in realmlists[realmlist])
                    {
                        writer.WriteStartElement("account");
                        writer.WriteElementString("accountname", accountInfo.Key);

                        //! Encrypt the password
                        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                        byte[] buffer = new byte[1024];
                        rng.GetBytes(buffer);
                        string salt = BitConverter.ToString(buffer);
                        rng.Dispose();
                        writer.WriteElementString("accountpassword", accountInfo.Value.Length == 0 ? String.Empty : accountInfo.Value.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt)));
                        writer.WriteElementString("entropy", salt);

                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();
            }

            Settings.Default.Save();
        }
Beispiel #28
0
        private void SaveLastUsedFields()
        {
            Settings.Default.ShowBasicInfo = userControl.checkBoxShowBasicInfo.Checked;
            Settings.Default.LockSmartScriptId = userControl.checkBoxLockEventId.Checked;
            Settings.Default.ListActionLists = userControl.checkBoxListActionlistsOrEntries.Checked;
            Settings.Default.AllowChangingEntryAndSourceType = userControl.checkBoxAllowChangingEntryAndSourceType.Checked;
            Settings.Default.PhaseHighlighting = userControl.checkBoxUsePhaseColors.Checked;
            Settings.Default.ShowTooltipsStaticly = userControl.checkBoxUseStaticTooltips.Checked;

            string lastStaticInfoPerTab = String.Empty;

            var objs = new List<object>();

            userControl.CurrentState.Save(userControl);

            int ctr = 0;

            foreach (SAIUserControlState state in userControl.States)
            {
                objs.Add(new
                {
                    Workspace = ctr++,
                    Value = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(state.ToStateObjects(), new CustomStateSerializer()))
                });
            }

            Settings.Default.LastStaticInfoPerTab = JsonConvert.SerializeObject(new { Workspaces = objs }, Formatting.Indented);

            if (SAI_Editor_Manager.FormState == FormState.FormStateLogin)
            {
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] buffer = new byte[1024];
                rng.GetBytes(buffer);
                string salt = BitConverter.ToString(buffer);
                rng.Dispose();

                Settings.Default.Entropy = salt;
                Settings.Default.Host = textBoxHost.Text;
                Settings.Default.User = textBoxUsername.Text;
                Settings.Default.Password = textBoxPassword.Text.Length == 0 ? String.Empty : textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                Settings.Default.Database = textBoxWorldDatabase.Text;
                Settings.Default.Port = CustomConverter.ToUInt32(textBoxPort.Text);
                Settings.Default.UseWorldDatabase = radioButtonConnectToMySql.Checked;
                Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;
            }

            Settings.Default.Save();
        }
        private void randomizeButton_Click(object sender, RoutedEventArgs e)
        {
            byte throwsNum;          // Ilość rzutów
            byte cubeTypeNum;        // Ilość ścianek kostki

            try {
                throwsNum = byte.Parse(throws.Text);
                cubeTypeNum = byte.Parse(cubeType.Text);

            } catch (Exception) { return; }

            var list = new List<Int32>();               // Lista wyrzuconych oczek
            rngCsp = new RNGCryptoServiceProvider();    // Service Kryptograficzny

            for (int i = 0; i < throwsNum; i++) {
                byte roll = RollDice((byte)cubeTypeNum);    // Funkcja losująca
                list.Add(roll);
            }

            rngCsp.Dispose();

            int sum = 0;
            foreach (var _ in list)         // Suma wszystkich oczek
                sum += _;

            var message = user.Name + " wyrzucił [" + throwsNum + "k" + cubeTypeNum + "] " + sum;

            if (throwsNum > 1) {
                message += " (";

                for (int i = 0; i < throwsNum; i++) // Wypisanie poszczególnych rzutów
                    message += list[i] + ((i == throwsNum - 1) ? "" : ",  ");

                message += ")";
            }

            message += ".";

            _mw.cubeThrow(message);
        }
Beispiel #30
0
        }//criarUsuario()

        public static int alterarSenhaUsuario(Usuario usuario)
        {
            //SqlDataReader dr = null;
            SqlConnection conn = null;
            SqlCommand cmd = null;
            SqlTransaction trans = null;
            RNGCryptoServiceProvider rnd;
            //String strSql = "UPDATE id_usuario from Usuario where email='" + novousuario.Email + "'";

            try
            {
                conn = new SqlConnection(ConnString);
                conn.Open();
                cmd = conn.CreateCommand();
                cmd.CommandType = System.Data.CommandType.Text;

                rnd = new RNGCryptoServiceProvider();
                byte[] salt = new byte[20];
                rnd.GetBytes(salt);
                rnd.Dispose();

                String strSalt = byteArray2String(salt);

                cmd.CommandText = "UPDATE Usuario set password = '******', salt='" + strSalt + "' where id_usuario = ";
                cmd.CommandText += usuario.IdUsuario.ToString();

                trans = conn.BeginTransaction();
                cmd.Transaction = trans;
                cmd.ExecuteNonQuery();
                trans.Commit();
                return 0;//sucesso
            }
            catch
            {
                //if (dr != null) dr.Close();
                trans.Rollback();
                return 1;//erro
            }
            finally
            {
                //if (dr != null) dr.Close();
                if (conn != null) conn.Close();
            }
        }//alterarSenhaUsuario()
Beispiel #31
0
        // Returns a cryptographically strong random 8.3 string that can be 
        // used as either a folder name or a file name.
        public static String GetRandomFileName()
        {
            // 5 bytes == 40 bits == 40/5 == 8 chars in our encoding
            // This gives us exactly 8 chars. We want to avoid the 8.3 short name issue
            byte[] key = new byte[10];

            // RNGCryptoServiceProvider is disposable in post-Orcas desktop mscorlibs, but not in CoreCLR's
            // mscorlib, so we need to do a manual using block for it.
            RNGCryptoServiceProvider rng = null;
            try
            {
                rng = new RNGCryptoServiceProvider();

                rng.GetBytes(key);
                // rndCharArray is expected to be 16 chars
                char[] rndCharArray = Path.ToBase32StringSuitableForDirName(key).ToCharArray();
                rndCharArray[8] = '.';
                return new String(rndCharArray, 0, 12);
            }
            finally
            {
                if (rng != null)
                {
                    rng.Dispose();
                }
            }
        }
        /// <summary>
        /// Prova a generare un identificativo di 16 byte sicuro dal punto di vista crittografico, restituendo true
        /// se la procedura viene completata correttamente. In caso contrario, viene impostato l'errore esplicativo
        /// e il metodo restituisce false.
        /// </summary>
        /// <param name="id">l'identificativo generato in modo sicuro, oppure null in caso di errore</param>
        /// <param name="error">l'eventuale errore impostato qualora si dovessero verificare dei problemi</param>
        /// <returns>true se l'identificativo viene generato correttamente, altrimenti false</returns>
        /// <remarks>
        /// Se l'identificativo viene generato correttamente, l'oggetto dedicato all'eventuale errore viene impostato
        /// al valore null, altrimenti al suo interno vengono impostati il codice d'errore e un identificativo che lo
        /// identifica univocamente sul server, oltre ad effettuare il logging dell'errore.
        /// </remarks>
        public bool TryGetRandomId(out string id, out ServiceFault error)
        {
            bool result;
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            try
            {
                byte[] randomBytes = new byte[16];
                rng.GetBytes(randomBytes);

                Guid guid = new Guid(randomBytes);

                id = guid.ToString();
                error = null;
                result = true;
            }
            catch (CryptographicException e)
            {
                HandleError(e.ToString(), ServiceFaultCode.TaskGenerateRequestIdFailed, out error);
                id = null;
                result = false;
            }
            finally
            {
                rng.Dispose();
            }

            return result;
        }
Beispiel #33
0
        private void StartExpandingToMainForm(bool instant = false)
        {
            if (radioButtonConnectToMySql.Checked)
            {
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                byte[] buffer = new byte[1024];
                rng.GetBytes(buffer);
                string salt = BitConverter.ToString(buffer);
                rng.Dispose();

                Settings.Default.Entropy = salt;
                Settings.Default.Host = textBoxHost.Text;
                Settings.Default.User = textBoxUsername.Text;
                Settings.Default.Password = textBoxPassword.Text.Length == 0 ? String.Empty : textBoxPassword.Text.ToSecureString().EncryptString(Encoding.Unicode.GetBytes(salt));
                Settings.Default.Database = textBoxWorldDatabase.Text;
                Settings.Default.AutoConnect = checkBoxAutoConnect.Checked;
                Settings.Default.Port = XConverter.ToUInt32(textBoxPort.Text);
                Settings.Default.UseWorldDatabase = true;
                Settings.Default.Save();
            }

            ResetFieldsToDefault();

            if (radioButtonConnectToMySql.Checked)
                Text = "SAI-Editor " + applicationVersion + " - Connection: " + textBoxUsername.Text + ", " + textBoxHost.Text + ", " + textBoxPort.Text;
            else
                Text = "SAI-Editor " + applicationVersion + " - Creator-only mode, no database connection";

            if (instant)
            {
                Width = MainFormWidth;
                Height = MainFormHeight;
                formState = FormState.FormStateMain;
                FinishedExpandingOrContracting(true);
            }
            else
            {
                formState = FormState.FormStateExpandingOrContracting;
                timerExpandOrContract.Enabled = true;
                expandingToMainForm = true;
            }

            foreach (Control control in controlsLoginForm)
                control.Visible = false;

            foreach (Control control in controlsMainForm)
                control.Visible = instant;

            panelPermanentTooltipTypes.Visible = false;
            panelPermanentTooltipParameters.Visible = false;
        }
Beispiel #34
0
 public static string GetRandomFileName()
 {
     byte[] numArray = new byte[10];
       RNGCryptoServiceProvider cryptoServiceProvider = (RNGCryptoServiceProvider) null;
       try
       {
     cryptoServiceProvider = new RNGCryptoServiceProvider();
     cryptoServiceProvider.GetBytes(numArray);
     char[] chArray = Path.ToBase32StringSuitableForDirName(numArray).ToCharArray();
     chArray[8] = '.';
     return new string(chArray, 0, 12);
       }
       finally
       {
     if (cryptoServiceProvider != null)
       cryptoServiceProvider.Dispose();
       }
 }