Random Password Generator - using Perl

published 01.Jan.2002

While working on a recent project, I needed some code to generate a random password for new users who registered with the system. The subroutine below demonstrates how you can generate random passwords of different lengths using Perl.

Random Password Generator - Perl Code

sub randomPassword {
my $password;
my $_rand;

my $password_length = $_[0];
	if (!$password_length) {
		$password_length = 10;
	}

my @chars = split(" ",
	"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 - _ % # |
	0 1 2 3 4 5 6 7 8 9");

srand;

for (my $i=0; $i <= $password_length ;$i++) {
	$_rand = int(rand 41);
	$password .= $chars[$_rand];
}
return $password;
}

Copy and paste the above subroutine into your Perl script. If you leave the password length parameter out when calling the routine, the code will create a password which is 10 characters long.

Example useage:

create a password which is 6 characters long

 my $password = randomPassword(6);

print a password which is 12 characters long

 print "password = ", randomPassword(12);

What Next?

Bookmark this article at :-

 

 

About Author:
I'm a father, husband, and a software developer who works for the NHS. more »

Sections :
« Articles
« Contact


 

FreeImage - an open source library project for developers who would like to support popular graphics image formats like PNG, BMP, JPEG, TIFF.