#!/usr/bin/perl

# seed_random()
# Seeds the random number generator, if needed
sub seed_random
{
if (!$main::done_seed_random) {
        if (open(RANDOM, "/dev/urandom")) {
                local $buf;
                read(RANDOM, $buf, 4);
                close(RANDOM);
                srand(time() ^ $$ ^ $buf);
                }
        else {
                srand(time() ^ $$);
                }
        $main::done_seed_random = 1;
        }
}

$LONGCLAVE=12;
@CLAVE=("0","1","2","3","4","5","6","7","0","1","2","3","4","5","6","7","0","1","2","3","4");

# cifrar( text, length(text), key, length(key),results)
# return text_cifrar
sub cifrar
{
	local $i,$pos;
        local @buffer;
        local @string_arr;

        &seed_random();
	for ( $pos = 0; $pos < $_[3]; $pos++ ) {
                $i=int(rand($_[3]));
                $string_arr[$pos]=${$_[2]}[$i];
	}
	if (($_[1] + 2) >= $_[3]) {
		$pos = 1;
	} else {
		$pos = int(rand($_[3] - ($_[1] + 2)));
	}
        if ( $pos < 1 ) { $pos=1; }
	$string_arr[$pos - 1] = '\\';
        for ( $i=0 ; $i < ($_[1]+1) ; $i++ ) {
        	$string_arr[$pos+$i]=${$_[0]}[$i];
        }
	$string_arr[$pos + $_[1]+1] = '\\';

	for ( $i = 0; $i < $_[3]; $i++) {
		$buffer[$i]= $string_arr[$i] ^ ${$_[2]}[$i];
                ${$_[4]}.=$buffer[$i];
        }
       return; 

}

# descifrar( text, key, length(key),results)
# return text_cifrar
sub descifrar
{
	
	local $i,$tobuff;
        local @buffer;

	for ( $i = 0; $i < $_[2]; $i++) {
		$buffer[$i] = ${$_[0]}[$i] ^ ${$_[1]}[$i];
        }

        $tobuff="0";
	for ( $i = 0; $i < $_[2]; $i++)  {
		if ($buffer[$i] eq '\\' )  {
                    if ( $tobuff eq "1" ) { 
                         $tobuff="0";
                    } elsif ( $tobuff eq "0" ) {
                         $tobuff="1";
                         next;
                    }
		}
                if ( $tobuff eq "1" ) { ${$_[3]}.=$buffer[$i]; }
        }

	return;
}
	@texto =();

        $lon=length($ARGV[0]); 
	for ( $i = 0; $i < $lon;$i++) {
            $texto[$i]=substr($ARGV[0],$i,1);
        }
	&cifrar(\@texto, $#texto, \@CLAVE, $LONGCLAVE,\$string_cif);
    
	@texto =();
        $lon=length($string_cif); 
	for ( $i = 0; $i < $lon;$i++) {
            $texto[$i]=substr($string_cif,$i,1);
        }
        $string_descif="";
	&descifrar(\@texto, \@CLAVE, $lon,\$string_descif);
	
       print "$ARGV[0] --- \"$string_cif\" -$lon- $string_descif\n";

