PM/GPG.pm

68 lines
1.5 KiB
Perl
Raw Normal View History

2014-04-28 14:07:01 +04:00
# GPG layer for encrypt/decrypt passwords database
2014-04-28 11:51:50 +04:00
package GPG;
2014-05-06 00:40:26 +04:00
# Debug
use Data::Dumper;
2014-04-28 11:51:50 +04:00
sub new {
2014-04-28 14:07:01 +04:00
my $class = shift;
2014-05-06 00:40:26 +04:00
my $home = $ENV{HOME};
2014-04-28 14:07:01 +04:00
my $db = $home . "/.PM/db.sqlite";
my $self = { _db => $db, };
2014-04-28 11:51:50 +04:00
bless $self, $class;
return $self;
}
2014-04-28 14:07:01 +04:00
# Encrypt sqlite database with default key
# and save it in config dir
sub encrypt_db {
my ( $self, $file ) = @_;
my $db = $self->{_db};
2014-04-28 16:13:19 +04:00
# Remove old database
@rm_db = ( "rm", "-f", "$db" );
system(@rm_db) == 0 or die "Cannot remove old database: $!\n";
2014-05-06 00:40:26 +04:00
# gpg --output test.gpg --encrypt test -a --default-recipient-self
2014-04-28 14:07:01 +04:00
@enc_cmd = (
2014-05-06 00:40:26 +04:00
"gpg", "--output", "$db",
"-a", "--default-recipient-self",
"--encrypt", "$file",
2014-04-28 14:07:01 +04:00
);
2014-05-06 00:40:26 +04:00
2014-04-28 16:13:19 +04:00
system(@enc_cmd) == 0
or die "Cannot encrypt!\nDecrypted file: $file\nTraceback: $!\n";
2014-04-28 14:07:01 +04:00
# Remove unencrypted file
2014-04-28 16:13:19 +04:00
@rm_cmd = ( "rm", "-f", "$file" );
2014-04-28 14:07:01 +04:00
system(@rm_cmd) == 0 or die "Cannot remove file $file: $!\n";
2014-04-28 16:13:19 +04:00
return 0;
2014-04-28 14:07:01 +04:00
}
# Decrypt database, save it in new place
# and return path to file
sub decrypt_db {
my ($self) = @_;
my $db = $self->{_db};
2014-05-06 00:40:26 +04:00
my $gpg = '/usr/bin/gpg';
2014-04-28 14:07:01 +04:00
# Generate random file name
my @chars = ( "A" .. "Z", "a" .. "z" );
my $string;
$string .= $chars[ rand @chars ] for 1 .. 10;
my $file = '/tmp/' . 'pm.' . $string;
# gpg --output /tmp/decryptfile --decrypt $db
2014-05-06 00:40:26 +04:00
@dec_cmd = ( "$gpg", "--output", "$file", "--decrypt", "$db" );
system(@dec_cmd) == 0 or die "Cannot decrypt $db: $!\n";
2014-04-28 14:07:01 +04:00
return $file;
}
1;