#
# $Id: Password.pm 3 2007-11-11 15:38:26Z tmr $
#

use strict;
use warnings;

use Crypt::CBC;

sub getCryptoProvider {

  my $key         = pack ("H*", shift);
  my $iv          = pack ("H*", shift);

  my $crypt  = new Crypt::CBC (-cipher      => 'Crypt::OpenSSL::AES',
                               -key         => $key,
                               -iv          => $iv,
                               -blocksize   => 16,
                               -keysize     => 32,
#                               -padding     => 'oneandzeroes',
                               -padding     => 'standard', # means PKCS5
                               -header      => 'none', # we have our own IV
                               -regenerate_key => 0
                              );

  return $crypt;
}

sub getSecure4Net {

  my $insecurePwd = shift;
  my $crypt       = &getCryptoProvider (shift, shift);
  my $secure      = $crypt->encrypt_hex ($insecurePwd);
#  my $secure      = $crypt->encrypt ($insecurePwd);

  return $secure;
#  return (unpack ("H*", $secure));
}

sub getInSecure4Net {

  my $securePwd   = shift; # pack ("H*", shift);
  my $crypt       = &getCryptoProvider (shift, shift);
#  my $insecure    = $crypt->decrypt ($securePwd);
  my $insecure    = $crypt->decrypt_hex ($securePwd);

  return $insecure;
}

my $iv  = '0' x 32;
#my $key = unpack ("H*", Crypt::CBC->random_bytes (32));
my $key = "213fd60a7fa98807afd292476c6b5dfb213fd60a7fa98807afd292476c6b5dfb";
#"b7a08f20cdd82d5625f5504f9cf6053240f742c0cee6e057f8065e8877dc9bee";
my $pwd = "425a683131415926535914858f8400004189007fe03f003001392906a790082414c001341214c48a7e9329b5a12a69a69118da6c6d19afb58fbeafbfa7979344cc1b2855c2fd79bf6f7f74bf1e4baccfed9646674fd197262028c05ae9d637996871bd6e16ba90124a5488c71b7448d91e554fa8699113d87ba3cc373c98382a0b863a24e8826ea7cb470772b418d0c86e897eca3ebd6c7ccf39f319fb927769f036753f432fa698ecfb76140f24515290b8dcd05a9fac44f01a654d8c9e602eb573ede666ac6e035f83c4cd0a121510db50652290d03a901e4a2c61aed52d11192689a62d3137fe2ee48a70a120290b1f08";
#&getSecure4Net ('Hello Erlang!', $key, $iv);
printf ("%s %s %s\n", $pwd, $key, $iv);
printf ("FROM C#: 38fca29b41b01beabb234e4184e18811\n");
printf ("%s %s %s\n", &getInSecure4Net ($pwd, $key, $iv), $key, $iv);
printf ("DECRYPT FROM C# >>>%s<<<\n", &getInSecure4Net ("38fca29b41b01beabb234e4184e18811", $key, $iv));

use Crypt::OpenSSL::AES;
my $cipher = new Crypt::OpenSSL::AES (pack ("H*", $key));
$pwd =  $cipher->encrypt (pack ("H*", "48656c6c6f2045726c616e6721030303")); # with PKCS#7 padding
printf ("%s %s\n", unpack ("H*", $pwd), $key);

# vim: fdm=syntax:fdn=3:tw=74:ts=2:syn=perl
