|
|
|
@ -15,6 +15,17 @@ use Digest::MD5 qw(md5); |
|
|
|
|
use bytes; |
|
|
|
|
|
|
|
|
|
our $VERSION = '2.0.0'; |
|
|
|
|
my $newIv; |
|
|
|
|
|
|
|
|
|
BEGIN { |
|
|
|
|
eval { require Crypt::URandom; Crypt::URandom::urandom(16) }; |
|
|
|
|
if ($@) { |
|
|
|
|
$newIv = sub { return md5( rand() . time . {} ) }; |
|
|
|
|
} |
|
|
|
|
else { |
|
|
|
|
$newIv = sub { return Crypt::URandom::urandom(16) }; |
|
|
|
|
} |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
our $msg; |
|
|
|
|
|
|
|
|
@ -41,11 +52,11 @@ sub new { |
|
|
|
|
# @param key that secondary key |
|
|
|
|
# @return Crypt::Rijndael object |
|
|
|
|
sub _getCipher { |
|
|
|
|
my ( $self, $key ) = @_; |
|
|
|
|
my ( $self, $key, $iv ) = @_; |
|
|
|
|
$key ||= ""; |
|
|
|
|
$self->{ciphers}->{$key} ||= |
|
|
|
|
my $cipher = |
|
|
|
|
Crypt::Rijndael->new( md5( $self->{key}, $key ), $self->{mode} ); |
|
|
|
|
return $self->{ciphers}->{$key}; |
|
|
|
|
return $cipher; |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
## @method string encrypt(string data) |
|
|
|
@ -59,7 +70,12 @@ sub encrypt { |
|
|
|
|
my $l = bytes::length($data) % 16; |
|
|
|
|
$data .= "\0" x ( 16 - $l ) unless ( $l == 0 ); |
|
|
|
|
|
|
|
|
|
eval { $data = encode_base64( $self->_getCipher->encrypt($data), '' ); }; |
|
|
|
|
my $iv = $newIv->(); |
|
|
|
|
eval { |
|
|
|
|
$data = |
|
|
|
|
encode_base64( $iv . $self->_getCipher->set_iv($iv)->encrypt($data), |
|
|
|
|
'' ); |
|
|
|
|
}; |
|
|
|
|
if ($@) { |
|
|
|
|
$msg = "Crypt::Rijndael error : $@"; |
|
|
|
|
return undef; |
|
|
|
@ -81,7 +97,11 @@ sub decrypt { |
|
|
|
|
$data =~ s/%2F/\//ig; |
|
|
|
|
$data =~ s/%3D/=/ig; |
|
|
|
|
$data =~ s/%0A/\n/ig; |
|
|
|
|
eval { $data = $self->_getCipher->decrypt( decode_base64($data) ); }; |
|
|
|
|
$data = decode_base64($data); |
|
|
|
|
my $iv; |
|
|
|
|
$iv = bytes::substr( $data, 0, 16 ); |
|
|
|
|
$data = bytes::substr( $data, 16 ); |
|
|
|
|
eval { $data = $self->_getCipher->set_iv($iv)->decrypt($data); }; |
|
|
|
|
if ($@) { |
|
|
|
|
$msg = "Crypt::Rijndael error : $@"; |
|
|
|
|
return undef; |
|
|
|
|