#!/usr/bin/perl
#
# By Phil2k@gmail.com
#

$syntax="Syntax: $0 [-d | -m | -b | -2 | -5 | -M ] [-n] [<pass>]\nWhere:\n -d = crypt() with DES ( default method, resulting pass will have 13 characters )\n -m = crypt() with MD5 ( resulting pass will have 34 characters )\n -b = crypt() with blowfish ( not supported by all Linuxes !)\n -2 = crypt() with SHA-256 ( resulting pass will have 63 characters )\n -5 = crypt() with SHA-512 ( resulting pass will have 106 characters )\n -M = hash-less hexadecimal MD5 ( resulting pass will have 32 characters, needs \"Digest::MD5\" Perl Module ! )\n -n = don't append new-line character at output\n";

$pass="";
$method="";
$hash_len=2;
$nl=1;
foreach $arg (@ARGV) {
  if ($arg=~/^-(.*)/) {
    $opt="$1";
    if ($opt eq "d") { $method=""; $hash_len=2; }
    elsif ($opt eq "m") { $method="1"; $hash_len=8; }
    elsif ($opt eq "b") { $method="2a"; $hash_len=16; }
    elsif ($opt eq "2") { $method="5"; $hash_len=16; }
    elsif ($opt eq "5") { $method="6"; $hash_len=16; }
    elsif ($opt eq "M") {
      use Digest::MD5 qw(md5_hex);
      $method="md5"; $hash_len=0;
      }
    elsif ($opt eq "n") { $nl=0; }
    else {
      print STDERR $syntax;
      exit(1);
      }
    }
  elsif (length($pass)) {
    print STDERR $syntax;
    exit(1);
    } else {
    $pass=$arg;
    }
  }
if (!length($pass)) {
  print "Enter a password for encryption: ";
  $pass=<STDIN>;
  chomp($pass);
  }

$hash_chars="abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ./";
if ($method eq "md5") {
  print md5_hex($pass).($nl?"\n":"");
  } else {
  print crypt($pass, (length($method)?'$'.$method.'$':'').&gen_hash($hash_len)).($nl?"\n":"");
  }


sub gen_hash() {
  my ($len)=@_;
  my $i;
  my $s="";
  my $hlen=length($hash_chars);
  for($i=0;$i<$len;$i++) {
    for($j=0;$j<$$/int(rand($$));$j++) { rand(); }
    for($j=0;$j<time()/int(rand(time()));$j++) { rand(); }
    $p=int(rand($hlen));
    $s.=substr($hash_chars, $p, 1);
    }
  return $s;
  }