0

My application is in asp.net 4.0 in which i want to generate password with 20 characters in which there is only 2 special characters allowed. To generate this password i have used below line if code. But this creates password with more than 2 special characters.

   string randomPassword = Membership.GeneratePassword(20,2);
rahul.deshmukh
  • 580
  • 2
  • 6
  • 23

1 Answers1

1

https://msdn.microsoft.com/en-us/library/system.web.security.membership.generatepassword%28v=vs.110%29.aspx

numberOfNonAlphanumericCharacters Type: System.Int32

The minimum number of non-alphanumeric characters (such as @, #, !, %, &, and so on) in the generated password.

I think you should create your own method if you want to have exactly 2 non-alphanumeric characters.

public string CreatePassword(int numberChar, int numberSpecialChar){
string password = "";
string specialChars = "&@~#'[|\\^/!?;"; //choose you own
int counterNonAlphanumeric = 0;
for (int i=0; i <numberChar-numberSpecialChar; i++){
    password += generateRandomChar();
    if (specialChars.Contains(password.Substring(password.Length-1, 1))){
        counterNonAlphanumeric +=1;
    }
}
if (counterNonAlphanumeric != numberSpecialChar){
    password += generateRandomSpecialChar();
    password += generateRandomSpecialChar();
}
}

I just improvised something to show the idea.

Hope it helps :P

Edit :

I found this (already created functions) : Generating Random Passwords Some functions are what you are searching for

Community
  • 1
  • 1
ninie1616
  • 141
  • 1
  • 7