Friday, March 20, 2015

How to Generate Random Password

From security point of view we need to create the unique passwords so no one can easily guess it.
To fulfill these features we can make use of Random class and generate the random numbers which is unique.

Here I am going to use one label, one text box and one button:
<form id="form1" runat="server">
    <div>   
    &nbsp;
        <asp:Label ID="lblPass"runat="server"Text="Random Password : "></asp:Label>
&nbsp;&nbsp;
        <asp:TextBox ID="txtRandom"runat="server"></asp:TextBox>
        <asp:Button ID="btnRandomNum"runat="server"onclick="btnRandomNum_Click"
            Text="Generate Password" />
   
    </div>
    </form>
</body>

</html>

In code behind we will write the actual logic on button click event as below:
protected voidbtnRandomNum_Click(object sender, EventArgs e)
        {
                    
            //Set password length

            string PasswordLength = "12";           

            //Characters allowed in the new password
            string allowedChars = "";
            allowedChars = "1,2,3,4,5,6,7,8,9,0";
            allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
            allowedChars += "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
            allowedChars += "~,!,@,#,$,%,^,&,*,+,?";

           
            //Create an array

            char[] sep = { ','};
            string[] arr = allowedChars.Split(sep);
            string randomPass = string.Empty;
            string tempPass = string.Empty;                     
            Random rand = new Random();
                      
            for (int i = 0; i < Convert.ToInt32(PasswordLength); i++)
            {
                tempPass = arr[rand.Next(0, arr.Length)];
                randomPass += tempPass;                                                          
                txtRandom.Text = randomPass;

            }

        }



Related Posts:

  • How to Generate Random PasswordFrom security point of view we need to create the unique passwords so no one can easily guess it.To fulfill these features we can make use of Random class and generate the random numbers which is unique.Here I am going to use… Read More
  • How to insert value into SharePoint list programmatically?Inserting value into SharePoint list programmatically:If we have list already created in SharePoint and want to add / insert value pro grammatically into the list then will use the below code.Suppose we have a list called Use… Read More