Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Membership Generate Password alphanumeric only password?

How can I use Membership.GeneratePassword to return a password that ONLY contains alpha or numeric characters? The default method will only guarantee a minimum and not a maximum number of non alphanumeric passwords.

like image 599
Curtis White Avatar asked Apr 12 '10 20:04

Curtis White


3 Answers

string newPassword = Membership.GeneratePassword(15, 0);
newPassword = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m => "9" );

This regular expression will replace all non alphanumeric characters with the numeric character 9.

like image 56
Curtis White Avatar answered Nov 16 '22 10:11

Curtis White


I realised that there may be ways of doing this. The GUID method is great, except it doesn't mix UPPER and lower case alphabets. In my case it produced lower-case only.

So I decided to use the Regex to remove the non-alphas then substring the results to the length that I needed.

string newPassword = Membership.GeneratePassword(50, 0); 

newPassword = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m => ""); 

newPassword = newPassword.Substring(0, 10);
like image 17
RealSollyM Avatar answered Nov 16 '22 11:11

RealSollyM


A simple way to get an 8 character alphanumeric password would be to generate a guid and use that as the basis:

string newPwd = Guid.NewGuid().ToString().Substring(0, 8);

If you need a longer password, just skip over the dash using substrings:

string newPwd = Guid.NewGuid().ToString().Substring(0, 11);
newPwd = newPwd.Substring(0, 8) + newPwd.Substring(9, 2); // to skip the dash.

If you want to make sure the first character is alpha, you could just replace it when needed with a fixed string if (newPwd[0] >= '0' && newPwd[0] <= '9')...

I hope someone can find this helpful. :-)

like image 15
Laura Blood Avatar answered Nov 16 '22 09:11

Laura Blood