Generate a random password in ASP. NET and asp.net
Method 1:
Use Sytem. Guid. NewGuid (). ToString () in. NET to generate a hexadecimal output of a 128bit number.
The generated characters consist of 0-9 and a-z, and may also contain "-" characters.
String strNewPW = System. Guid. NewGuid (). ToString ();
The result may be: 7f44aed7-f8a4-4229-b64a-6a3e50d920e0.
Take a look, remove the "-" character, the rest is a string consisting of 32 Arabic numbers and English letters, and then extract the string of the specified length according to your own requirements.
Intercept 8 digits:
String strNewPW = System. Guid. NewGuid (). ToString (). Replace ("-", ""). Substring (0, 8 );
Result: 7f44aed7
Method 2:
Implementation Method:
Protected void Page_Load (object sender, EventArgs e)
{
// Set the character range to a random string of uppercase/lowercase letters and numbers.
String strPwChar = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
// The Truncation length is 8.
String strNewPW = MakePassword (strPwChar, 8 );
Response. Write (strNewPW );
}
/// <Summary>
/// Generate a random string
/// </Summary>
/// <Param name = "strPwChar"> characters that can be used to input the generated random string </param>
/// <Param name = "intlen"> input the length of the generated random string </param>
Public static string MakePassword (string strPwChar, int intlen)
{
String strRe = "";
Int iRandNum;
Random rnd = new Random ();
For (int I = 0; I <intlen; I ++)
{
IRandNum = rnd. Next (strPwChar. Length );
StrRe + = strPwChar [iRandNum];
}
Return strRe;
}
The result is: qk81_61c.
The MakePassword method accepts two parameters. The strPwChar parameter specifies which characters can be used for the generated random password string, and intlen specifies the length of the generated random password string. With these two parameters, you can call the Next () method of the Random class to obtain an integer greater than or equal to 0 and less than the length of intlen, using this number as the index value, take random characters from available strings, take the specified password length as the number of cycles, connect the obtained characters in sequence, and finally obtain the required random password string.