package Email;

use Crypt::MD5;
use Crypt::DES_PP;
use strict;

use vars qw($SIZE $KEY $error);
$error = "";

$KEY = "43963712047693658245013857";
$SIZE= 16 ;


# signature: "Customer Name";

sub encrypt_email {
  my($class, $email, $key, $signature) = @_;
  my($md5, $hash, $cipher, $padd, $out, $x, $out2);
  chomp($email);
  $key = $KEY if (!$key);
  $key = substr($key,0,$SIZE);

  $signature = "storade" if (!$signature);

  $email = "Signature: $signature\n$email";

  $padd  = 8 - (length($email)% 8);
  $email .= " " x $padd;
  if (length($key) != $SIZE) {
     $error = "Invalid key";
     return undef;
  }

  eval {
    $md5    = new Crypt::MD5;
    $md5->add($email);
    $hash  = unpack("H*", $md5->digest());
    $email = "Hash_: $hash\n$email";

    $cipher= new Crypt::DES_PP($key);

    my($cnt);
    my $size = length($email) ;
    my $emailptr;
    $emailptr = $email;
    $out = unpack("H*",$cipher->encrypt(substr($emailptr,0,8)));

    for ($x=0; $x < length($email); $x+=8) {
       $emailptr = substr($emailptr, 8);
       $out .= unpack("H*",$cipher->encrypt(substr($emailptr,0,8)));
       if ($cnt++ % 1000 == 0) {
          my $s = sprintf("%5.2f", $x/$size*100);
          Debug->print2("Compression $s% complete..");
       }
    }
  };
  my $idx = 0; 
  my $len = length($out); 
  $out2 = "";
  while  ($idx < $len) {
     $out2  .= substr($out, $idx, 100) . "\n";
     $idx += 100;
  }
  if ($@) {
    $error = $@;
    return undef;
  } else {
    return $out2;
  }

}

sub decrypt_email {
  my($class, $enc0, $key) = @_;
  my ($enc, $cipher, $x, $out, $calc_hash, $hash,$ix, $idx);

  $key = $KEY if (!$key);
  $key = substr($key, 0, $SIZE);

  my $len = length($enc0); 
  $idx = 0;
  while ($idx < $len) {
    $enc .= substr($enc0, $idx, 100);
    $idx += 101;
  }
  chop($enc) if (substr($enc,-1) eq "\n");
  $enc = pack("H*", $enc);
  return () if (length($enc) % 8 != 0);

  if (length($key) != $SIZE) {
     $error = "Invalid key";
     return undef;
  }

  $cipher = new Crypt::DES_PP($key);

  for ($x=0 ; $x < length($enc); $x += 8) {
    $out .= $cipher->decrypt(substr($enc,$x,8));
  }
  $hash   = substr($out, 7,32);
  my $email  = substr($out,40);
  my $md5    = new Crypt::MD5;
  $md5->add($email);
  $calc_hash = unpack("H*", $md5->digest());
  if ($calc_hash ne $hash) {
    return ();
  } else {
    $ix = index($email, "\n");
    my $signature = substr($email, 11, $ix - 11);
    $email = substr($email, $ix+1);
    return ($signature, $email . "\n");
  }
}

1;
