A Replacement for Older htpasswd Programs

If you have a version of htpasswd that doesn't support the useful '-b' flag, you can replace it with this succinct Perl script instead!
#!/usr/bin/perl

if (! scalar @ARGV ) {
  print "Usage: htpasswd-b passwordfile user password\n";
  print "(this program automatically creates the pw file if needed.)\n";
  exit 0;
}

@saltsource = ('a'..'z', 'A'..'Z', '0'..'9','.','/');
$randum_num = int(rand(scalar @saltsource));
$salt = $saltsource[$randum_num];
$randum_num = int(rand(scalar @saltsource));
$salt .= $saltsource[$randum_num];

$outf=$ARGV[0];
$user=$ARGV[1];
$passwd=$ARGV[2];

if ($user && $passwd) {
  $encrypted = crypt($passwd, "$salt");

  if (-f $outf) { 
    open(OUT, ">>$outf") || die "htpasswd-b error: $!\n";
  } else {
    open(OUT, ">$outf") || die "htpasswd-b error: $!\n";
  }
  print OUT "$user:$encrypted\n";
  close(OUT);

  exit 0;
}

To Do: save this file as htpasswd-b, run perl -c htpasswd-b to make sure nothing's been broken in transit, then mark this as an executable script with chmod a+x htpasswd-b. You're ready to go!

From the book "Wicked Cool Shell Scripts" by Dave Taylor