How to generate random string or password with specific length and specific characters.


This C# code shows you how to generate random string or password with the specific length and specific characters you want in asp.net web application.

With this code we can generate random string. It is helpful for generating random password. Here we can choose the length of the string to generate. Also we can choose the characters which will be use to generate the string. In This code the allowed characters are defined in a string. The string name is "CharsList". This is done by the "Cryptography" or "RNGCryptoServiceProvider". To use this we have to add "System.Security.Cryptography" and "System.Text" Namespace. Now I am going to the implementation.
The code is given below:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
private string RandomString(int StrLength)
{
string CharsList = "abcdefghijklmnopqrstuvwxyz1234567890";
char[] chars = CharsList.ToCharArray();

RNGCryptoServiceProvider cryptoGen = new RNGCryptoServiceProvider();
byte[] ByteData = new byte[StrLength];
cryptoGen.GetBytes(ByteData);

StringBuilder ResultStr = new StringBuilder();
foreach (byte byt in ByteData)
{
ResultStr.Append(chars[byt % chars.Length]);
}
return ResultStr.ToString();
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = RandomString(8);
}
}


Comments

Author: Ram kumar Kangeyan07 Mar 2011 Member Level: Bronze   Points : 0

Hi MONOJ BHUINA,

Thanks for the information, its useful.

Thanks,
Ram



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: