If you don't specify a password to use on the command line, it will generate a random 15 character password for you.
NB: You really shouldn't use it with a password on the command line, as this can be seen by other users with the ps command while it's running. I've just done this to simplify the example. This code is a snippet, intended to be used in a larger script where the password would be read from a file or provided on STDIN.
#!/usr/bin/perl
#
#
#
use warnings;
use strict;
my $len = 15;
my $plaintext = shift;
if ( ! $plaintext ) {
my @chars;
for my $char (33 .. 126) {
push @chars, chr($char);
}
for (1..$len) {
$plaintext .= $chars[int(rand($#chars))];
}
}
my @schars = ('a'..'z','A'..'Z',0..9,'.','/');
my $salt = '';
for (1..8) {
$salt .= $schars[int(rand($#schars))];
}
my $crypted_pass = crypt($plaintext,'$1$' . $salt )
or die($!);
print "$plaintext\n$crypted_pass\n";
There are other tools to do this.
For example, on Debian Linux so far I know of:
$ dpkg -S /usr/bin/openssl
openssl: /usr/bin/openssl
$ dpkg -S /usr/bin/mkpasswd
whois: /usr/bin/mkpasswd
$ dpkg -S /usr/bin/makepasswd
makepasswd: /usr/bin/makepasswd
Usage:
$ openssl passwd -1 -stdin <<EOT
passwd
EOT
$1$nRGcgK4T$uI7mxwMxGUt6NQ.lyu42./
$ mkpasswd -5 -s <<EOT
> passwd
> EOT
$1$0rg1g/e9$rh1lfYHX9qkSVihZ9vBcd/
$ makepasswd --crypt-md5 --clearfrom=-
passwd
passwd $1$IEK./reC$UbqosXZvVn6Hv/2Zej.va/
I wanted to run it on Solaris, and I wanted to run it in a Perl program (because the rest of the program I was writing was in Perl)
The openssl and mkpasswd programs are compiled C binaries, makepasswd is written in Perl, but it uses Crypt::OpenSSL::Random to generate better randomness, and the box I needed to run it on didn't have that library.
I expect the rand() in Perl is quite random enough for my needs here!