2

How to generate a random password of fixed length in ASP.net (no GUID) ? After generating the random password, I need to email the password to the specified user.

user1554472
  • 49
  • 4
  • 9
  • This is how I usually do it, take a look: http://mvcbootstrap.codeplex.com/SourceControl/changeset/view/af97c313f0a0#MVCBootstrap%2fWeb%2fSecurity%2fPasswordGenerator.cs – Steen Tøttrup Jul 31 '12 at 05:23

5 Answers5

8

In the System.Web.Security namespace you'll find a way to generate passwords:

string pw = Membership.GeneratePassword(8, 1);

You can provide the length of the password in the first parameter. The second is to indicate the minimum number of non-alphanumeric characters in the generated password.

MSDN

Koen
  • 2,451
  • 1
  • 29
  • 42
3

Simply use Membership.GeneratePassword Method

// Generate a new 12-character password with 1 non-alphanumeric character.
  string password = Membership.GeneratePassword(12, 1);

Then use following links for reference to send your password in email as MailMessage Body.

Sending Mail Using C# via SMTP
Sending email in .NET through Gmail

Source: Configuring ASP.NET for sending Email

MailSettings for web.config

<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="from@yourdomain.com">
<network host="smtp server addresss" userName="username" password="password"
defaultCredentials="false" port="xxx" enableSsl="true"  />
</smtp>
</mailSettings>
</system.net>

Then use following code to faster mail delivery. you can configure your mail to use gmail smtp server etc, all depends on you.

    try
    {
    MailMessage mailMessage = new System.Net.Mail.MailMessage();
    mailMessage.To.Add(userEmailAddress);
    mailMessage.Subject = "Subject";
    mailMessage.Body = "your password should be in this section";
    var smtpClient = new SmtpClient();
    smtpClient.Send(mailMessage);
    return "Mail send successfully";
    }

catch (SmtpException ex)
{
return "Mail send failed:" + ex.Message;
}

If you want to create your own password there are lots of help regarding this on google.
How To: Generate a Random Password (C#/VB.NET)
Generate Random password using C#
Generating Random Number and String in C#
C# Random Password Generator
Random Password Generation

Hope this help.

Community
  • 1
  • 1
Niranjan Singh
  • 17,209
  • 2
  • 39
  • 70
1

I would use the Random function provided in this documentation: http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx

I typically create a character array or a string ("abcdefg...".ToCharArray();). This way that's whats chosen so we don't get random characters generated.

This isn't an uncommon functionality, especially with small groups with a single admin (teacher/student situation). I will say this functionality is undesirable in a normal situation of a one way encrypted password.

jamesbar2
  • 614
  • 7
  • 19
0

If You don't want to use Membership.GeneratePassword Method this is work for you.
Generate Random Number

 public int RandomNumber(int min, int max)
 {
        try
        {
            Random random = new Random();
            return random.Next(min, max);
        }
        catch (Exception)
        {

            throw;
        }

    }

Generate Random string

 public string RandomString(int size, bool lowerCase)
 {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
            return builder.ToString().ToLower();
        return builder.ToString();
 }

Combine and Get Unique Password

 public string GetPassword()
 {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(4, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(2, false));
        return builder.ToString();
 }

Send Password Via Gmail SMTP

  public void SendUsernamePassword(string Email,string UserName,string Password)
  {


        MailMessage mM = new MailMessage();
        mM.From = new MailAddress("YourGmailAccount@gmail.com");
        mM.To.Add(Email);
        mM.Subject = "Your Username and Password.";
        mM.Body = "Your Username and Password is:<br/>Username:" + UserName+ "<br/>" + "Password:" + Password;
        mM.IsBodyHtml = true;
        mM.Priority = MailPriority.High;
        SmtpClient sC = new SmtpClient("smtp.gmail.com");
        sC.Port = 587;
        sC.Credentials = new NetworkCredential("YourGmailAccount@gmail.com", "YourPassword");
        //sC.EnableSsl = true;
        sC.EnableSsl = true;
        sC.Send(mM);


  }
Shree
  • 18,997
  • 28
  • 86
  • 133
-2

i would advise against sending a password through email, because of the inherent risks associated, as well as the unnecessary complexity this adds to your application. it would be better to implement a password creation system directly in the most natural spot of your application. i realise the vagueness of "most natural spot", but this is because different applications have different design ideals. also here i use "application" in a broader sense than is usually used. examples of natural spots for password creation in websites with user accounts would be the account management, login, and registration pages. if the purpose of the password generator is to provide a temporary password that the user will change, then it is better to just let the user decide their password at registration. if you are still in need for a password generator after thoroughly considering the needs of the application, then you can use a random number generator piped into a converter to the desired character set. i would also urge you to do at least an internet search for information on the topic of a question before asking about on a forum, especially if it is a simple question, but even if it is not, you will likely find a tutorial within the first few pages of your favourite search engine. if there is already an easy to find solution to your problem then at best you'll have wasted the time of the friendly people who helped you out, and at worst, get either unfriendly answers, difficult to understand answers from busy people, shoddy help from inexperienced users, or an RTFM. if you have not found a solution with a cursory search of your favorite search engines or tutorial sites, and after say five minutes of contemplating what exactly your needs are, by all means, ask. asking before doing your own research increases the risk of appearing inconsiderate.

as a summary of my actual answer

  • random number generator
  • typecast to desired charset. it's that simple.

(if it's any more complicated than that in your preferred language, maybe reconsider your preferred language :p)