App-SimpleBackuper
view release on metacpan or search on metacpan
lib/App/SimpleBackuper/RegularFile.pm view on Meta::CPAN
}
use Digest::SHA qw(sha512_hex); # apt install libdigest-sha-perl
sub hash {
my($self) = @_;
my $hash = sha512_hex($self->{data});
#printf "\tsha512 is %s\n", $hash;
return $hash;
}
use Compress::Raw::Lzma; # apt install libcompress-raw-lzma-perl
sub compress {
my($self) = @_;
my $compression_level = $self->{options}->{compression_level};
# Because is useless
$compression_level = 0 if $self->{filepath} =~ /\.(jpg|jpeg|mp3|mp4|avi|mkv|mov|mpg|mpeg|nef)$/i;
my($z, $status) = Compress::Raw::Lzma::EasyEncoder->new(
Preset => $compression_level,
Check => LZMA_CHECK_SHA256,
AppendOutput => 1,
);
die "$status\n" if $status != LZMA_OK;
$status = $z->code($self->{data}, my $out);
die "$status\n" if $status != LZMA_OK;
$status = $z->flush($out);
die "$status\n" if $status != LZMA_STREAM_END;
my $ratio = length($out) / (length($self->{data}) || 1);
$self->{data} = $out;
return $ratio;
}
sub decompress {
my($self) = @_;
my($z, $status) = Compress::Raw::Lzma::AutoDecoder->new();
die "$status\n" if $status != LZMA_OK;
$status = $z->code($self->{data}, my $out);
confess $status if $status != LZMA_STREAM_END;
my $ratio = length($self->{data}) / length($out);
$self->{data} = $out;
return $ratio;
}
# key, iv
sub gen_keys { pack("C32", map {int rand 256} 1..32), pack("C16", map {int rand 256} 1..16) }
use Crypt::Rijndael; # apt install libcrypt-rijndael-perl
srand(time ^ $$ ^ (unpack("%L*", `head /dev/urandom`) * unpack("%L*", `head /dev/urandom`))); # For randomness
sub encrypt {
my($self, $key, $iv) = @_;
my $cipher = Crypt::Rijndael->new($key, Crypt::Rijndael::MODE_CBC());
$cipher->set_iv($iv);
$self->{data} = $cipher->encrypt($self->{data}
. "\0" x (length($self->{data}) % length($key) ? length($key) - length($self->{data}) % length($key) : 0)
) # aligning data for crypt. decompressor ignores it.
;
return;
}
sub decrypt {
my($self, $key, $iv) = @_;
my $cipher = Crypt::Rijndael->new($key, Crypt::Rijndael::MODE_CBC());
$cipher->set_iv($iv);
$self->{data} = $cipher->decrypt($self->{data});
return;
}
sub size { length shift->{data} }
sub data_ref {
my $self = shift;
if(@_) {
$self->{data} = shift;
confess if ref($self->{data}) ne 'SCALAR';
$self->{data} = ${ $self->{data} };
return $self;
} else {
return \$self->{data};
}
}
sub truncate {
my($self, $size) = @_;
$self->set_write_mode();
truncate($self->{handler}, $size) // die "$!\n";
return $self;
}
1;
( run in 1.851 second using v1.01-cache-2.11-cpan-e1769b4cff6 )