#!/usr/bin/perl -w

# enceypt, decrupt
package Crypt;
use strict;
use warnings;
use IPC::Open2;

BEGIN {
    use Exporter ();
    our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
    $VERSION = 1.00;                    # version for version checking
    @ISA = qw(Exporter);
    @EXPORT = qw(encrypt decrypt);
    @EXPORT_OK = qw();                  # optionally exported functions
}


sub encrypt
{
    my ( $pwd, $val ) = @_;
    local $/;
        
    ref( $val ) and die "Only scalars can be encrypted";
    open2( *RDRFH, *WTRFH, 'openssl', 'des3', '-e', '-a', '-A', '-salt', '-k',
           $pwd ) or die "OpenSSL encryption failed";
    print WTRFH $val;
    close( WTRFH );
    undef $/;
    $val = <RDRFH>;
    return $val;
}

sub decrypt
{
    my ( $pwd, $val ) = @_;
    local $/;

    open2( *RDRFH, *WTRFH, 'openssl', 'des3', '-d', '-a', '-A','-salt', '-k',
           $pwd ) or die "OpenSSL decryption failed";
    print WTRFH $val, "\n";
    close( WTRFH );
    undef $/;
    $val = <RDRFH>;
    return $val;
}

1;


# sub encode
# {
#     ref( $_[0] ) eq 'ARRAY' and return encode_arr($_[0]);
#     ref( $_[0] ) eq 'HASH' and return encode_hash($_[0]);
#     ref( $_[0] ) or return encode_scalar($_[0]);

#     die "Unhandled type " . ref( $_[0] );
# }        



# sub encode_arr
# {
#     my $arr = shift;
#     my $tx = '[';

#     foreach my $elem (@{$arr}) {
#         $tx .= encode( $elem ) . ",";
#     }
#     return $tx .']';
# }

# sub encode_hash
# {
#     my $hash = shift;
#     my $tx = '{';

#     foreach my $key ( keys( %{$hash}) ) {
#         $tx .= encode( $key ) . "=>" . encode( $hash->{$key} ) . ",";
#     }
#     return $tx .'}';
# }

# sub encode_scalar
# {
#     my $val = shift;

#     $val =~ s/\\/\\\\/g;
#     $val =~ s/\'/\\\'/g;
#     $val =~ s/\"/\\\"/g;
    
#     return "\"$val\"";
# }





