Generating Random Passwords in JavaScript

1. In any convenient location, create a new directory named “RandomPasswordGenerator”.

2. In the newly create RandomPasswordGenerator directory, create a new text file named “RandomPasswordGenerator.html” containing the following text.

<html>
<body>
<script type='text/javascript' src='RandomPasswordGenerator.js'></script>
</body>
</html>

3. Still in the newly created RandomPasswordGenerator directory, create a new text file named “RandomPasswordGenerator.js” containing the following text.

var url = window.location.href;
var passwordParameterText = "?PasswordLength=";

var passwordLengthInCharacters = 10;

var indexOfPasswordParameterName = url.indexOf
(
    passwordParameterText
);

if (indexOfPasswordParameterName > 0)
{
    var passwordLengthAsString = url.substring
    (
        indexOfPasswordParameterName
        + passwordParameterText.length
    );

    passwordLengthInCharacters = parseInt
    (
        passwordLengthAsString
    );
}

var charactersPossible =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    + "abcdefghijklmnopqrstuvwxyz"
    + "0123456789";

var numberOfCharactersPossible = charactersPossible.length;

var passwordSoFar = "";

for (var i = 0; i < passwordLengthInCharacters; i++)
{
    var characterIndex =
        Math.random()
        * numberOfCharactersPossible 

    var characterCurrent = charactersPossible.charAt(characterIndex);

    passwordSoFar += characterCurrent;
}

alert("The password is: " + passwordSoFar );

4. Double-click the icon of the RandomPasswordGenerator.html file to open it in a browser (or, if file associations are not set up to do this automatically, open a web browser and open the .html file manually).  A popup dialog will appear that displays a random alphanumeric password of the default length.

5. If a password of a different length is desired, append the query string “?PasswordLength=nnn” to the end of the URL in the browser’s address bar, and substitute the desired length in characters for “nnn”.

This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s