# Copyright (C) 2005 FishGrove Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# $Id: MyCrypt.pm,v 1.4 2006/03/07 14:39:11 slash5234 Exp $

package Affelio::misc::MyCrypt;
{
    use lib "../../../extlib";
    use Crypt::RC5;

    use Exporter;
    @Affelio::misc::MyCrypt::ISA = "Exporter";
    @Affelio::misc::MyCrypt::EXPORT = qw (generate_password msg_encrypt msg_decrypt url_encode url_decode verify_password);

    ########################################################################
    sub generate_password{
	@chara=('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','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');
	for($i=0; $i<9; $i++){
	    $str .= $chara[int(rand($#chara+1))];
	}
	return $str;
    }

    ########################################################################
    sub msg_encrypt{
	my $plaintext = shift;
	my $key = shift;
	if ($key eq ""){
	    die "msg_encrypt: Key is not defined!";
	}
	
	my $ref = Crypt::RC5->new($key, 12 );
	return( $ref->encrypt( $plaintext ) );
    }

    ########################################################################
    sub msg_decrypt{
	my $ciphertext = shift;
	my $key = shift;
	if ($key eq ""){
	    die "msg_decrypt: Key is not defined!";
	}
	
	my $ref = Crypt::RC5->new($key, 12 );
	return($ref->decrypt( $ciphertext ));
    }

    ########################################################################
    sub url_encode{
	my $str = shift;
	$str =~ s/(\W)/sprintf("%%%02X", ord($1))/ego;
	return($str);
    }

    ########################################################################
    sub url_decode{
	my $str = shift;
	$str =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr(hex($1))/ego;
	return($str);
    }

    ########################################################################
    sub verify_password{
	$passwd = shift;
	$epasswd =  shift;
	
	if ($epasswd eq crypt($passwd, $epasswd)) {
	    return(1);
	}else{
	    return(-1);
	}
    }
    
}
1;
