Skip to content

Instantly share code, notes, and snippets.

@krimdomu
Created June 30, 2014 12:26
Show Gist options
  • Save krimdomu/96fa06fa4d393c69d974 to your computer and use it in GitHub Desktop.
Save krimdomu/96fa06fa4d393c69d974 to your computer and use it in GitHub Desktop.
encryption with openssl
package Rex::Ext::Encryption::OpenSSL;
use Rex -base;
use Carp;
use Crypt::OpenSSL::RSA;
use MIME::Base64;
require Exporter;
use base qw(Exporter);
use vars qw(@EXPORT);
use constant DEFAULT_CERT_FILE => '/etc/rex/enc.key';
@EXPORT = qw(decrypt_string);
=begin decrypt_string($file, $str)
Decrypt a given string with the given SSL key file.
=cut
sub decrypt_string {
my ($file, $str) = @_;
if(! $file) { return; }
if(! -f $file) {
$str = $file;
$file = DEFAULT_CERT_FILE;
}
confess 'No key file found.' if(! -f $file);
my $key_string = _get_priv_key($file);
my $o = Crypt::OpenSSL::RSA->new_private_key($key_string);
$o->use_sslv23_padding;
my @strr = split("\n", decode_base64($str));
my $dec = "";
for my $str (@strr) {
$dec .= $o->decrypt(decode_base64($str));
}
return $dec;
}
sub _get_priv_key {
my ($file) = @_;
if(! $file) {
$file = DEFAULT_CERT_FILE;
}
my @lines = IO::File->new($file, 'r')->getlines;
join "\n", @lines;
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment