Generate Random Password in VB.Net

This article shows how to generate Random Password using vb.net
  • 7192

 In this article you will get the knowledge to generate the random password at run-time.

Example:

<%
@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
    <
title>Random Password</title>
</
head>
<
body>
    <
form id="form1" runat="server">
        <
table width="300px">
            <
tr align="center">
                <
td>
                    <
fieldset>
                        <
legend style="border: none; font-weight: bold; color: #660099; font-size: 15pt; font-family: Segoe UI">Random Password&nbsp;</legend> 
                        <asp:Label ID="Label1" runat="server" ForeColor="navy" Text="Enter Password Length:"></asp:Label>
                        <
asp:TextBox ID="TextBoxPasswordLength" runat="server" Width="100" MaxLength="2"></asp:TextBox><br/>
                        <
asp:Label ID="LabelShowPwd" runat="server" ForeColor="navy"></asp:Label><br />
                        <
asp:Button ID="ButtonOk" runat="server" Text=" Ok " OnClick="ButtonOk_Click" /> 
                    </fieldset>
                </
td>
            </
tr>
        </
table>
    </
form>
</
body>
</
html 

Code behind will go like this: 
Imports Microsoft.VisualBasic
Imports System
Imports System.Data
Imports System.Configuration
Imports System.Web
Imports System.Web.Security
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls 
Partial Class _Default Inherits System.Web.UI.Page

Protected
 Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)

If
 IsPostBack Then
LabelShowPwd.Text = "Please enter a password length."
End If
End
 Sub 
Public Shared Function CreateRandomPassword(ByVal PasswordLength As IntegerAs String
Dim
 _allowedChars As String = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
Dim randomNumber As New Random()
Dim chars(PasswordLength - 1) As Char
Dim
 allowedCharCount As Integer = _allowedChars.Length
For i As Integer = 0 To PasswordLength - 1
chars(i) = _allowedChars.Chars(
CInt(Fix((_allowedChars.Length) * randomNumber.NextDouble())))
Next i
Return New String(chars)
End Function

Protected
 Sub ButtonOk_Click(ByVal sender As ObjectByVal e As EventArgs)
If TextBoxPasswordLength.Text <> "" Then
Dim
 password As String = TextBoxPasswordLength.Text.ToString()
LabelShowPwd.Text = 
"Your generated password is: " & CreateRandomPassword(Integer.Parse(password))
End If
End
 Sub 
End Class

OutPut: Enter the length, Suppose I want to generate 10 characters of password then I have to enter 10 in the textbox as follows:

 img1.JPG 

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.