C# 亂數密碼 - 數字與英文湊成

  • 4497
  • 0
  • 2017-11-28

C# 亂數密碼 - 數字與英文湊成


namespace test_pw
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
            int passwordLength = 8;//密碼長度
            char[] chars = new char[passwordLength];
            Random rd = new Random();

            for (int i = 0; i < passwordLength; i++)
            {
                //allowedChars -> 這個String ,隨機取得一個字,丟給chars[i]
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }

            string pwd =  new string(chars);
            Response.Write(pwd);
        }
    }
}

資料來源:

https://madskristensen.net/blog/generate-random-password-in-c/