#!/usr/bin/perl -w
#
# __copy1__
# __copy2__
#
# original code based on openLDAP Faq-O-Matic examples
# modified by Lorenzo Canovi to get password from stdin also, and
# to generate SSHA e SMD5 (salted version of SHA1 e MD5)
#
# the encoded passwords are printed on stdout, ordered by strength
# (more secure to less secure): note that the not-salted version
# are two-ways encryptions, and salted are one-way

use Digest::SHA1;
use Digest::MD5;
use MIME::Base64;

my $password;
my $result;
my $digest;
my $salt;
my @chars;


CASE: {
	if (@ARGV == 0) {
		system( "stty -echo 2>/dev/null" );
		printf( "enter token to encrypt: " );
		$password	= <>;
		system( "stty echo 2>/dev/null" );
		printf( "\n" );
		chomp( $password );
		last CASE;
	}
	if (@ARGV == 1) {
		$password	= $ARGV[0];
		last CASE;
	}
	printf( "usage: %s [password]\n", $0 );
	exit( 1 );
}


# salt generation (for salt based encodings)
#
@chars	= ( "A" .. "Z", "a" .. "z", 0 .. 9, qw(. /) );
$salt	= join( "", @chars[ map { rand @chars} ( 1 .. 4 ) ] );


# generate and print the SSHA hash (salted)
#
$digest = new Digest::SHA1;
$digest->add( $password );
$digest->add( $salt );
$result	= '{SSHA}' . encode_base64( $digest->digest,'' );
printf( "%s\n", $result );


# generate and print the SMD5 hash (salted)
#
$digest = new Digest::MD5;
$digest->add( $password );
$digest->add( $salt );
$result = '{SMD5}' . encode_base64( $digest->digest,'' );
printf( "%s\n", $result );


# generate and print the CRYPT version (salted)
#
$result = '{crypt}' . crypt( $password, $salt );
printf( "%s\n", $result );


# generate and print the SHA1 hash (not salted)
#
$digest = new Digest::SHA1;
$digest->add( $password );
$result	= '{SHA}' . encode_base64( $digest->digest,'' );
printf( "%s\n", $result );


# generate and print the MD5 hash (not salted)
#
$digest = new Digest::MD5;
$digest->add( $password );
$result = '{MD5}' . encode_base64( $digest->digest,'' );
printf( "%s\n", $result );


exit( 0 );
