here is the complete code that uses part of the code mentioned above and part taken from Perlmonk. The script first asks for the username and password of the user, encrypts and saves it in a .crypt file. Then it reads from it, decrypts and shows the source text. The second time, he will use the existing user credentials.
use Crypt::Rijndael;
use IO::Prompter;
use Crypt::CBC;
my $key = "a" x 32;
my $cipher = Crypt::CBC->new( -cipher => 'Rijndael', -key => $key );
my @plaintext;
my @ciphertext;
my $file_name = ".crypt";
my $file;
unless ( open ( $file, '<:encoding(UTF-8)', $file_name) ) {
open ( $file, '>', $file_name);
$plaintext[0]= prompt "Username:";
$plaintext[1]= prompt "Password:", -echo => '';
print "#################################################################################\n";
print "# User credentials will be encrypted and stored in .crypt file and same is #\n";
print "# reused next time. If you need to add new user credentials delete the .crypt #\n";
print "# file and re run the same script. #\n";
print "#################################################################################\n";
$plaintext[0]=~ s/^\s*(.*?)\s*$/$1/;
$plaintext[1]=~ s/^\s*(.*?)\s*$/$1/;
while($plaintext[0] =~ /^\s*$/){
$plaintext[0]= prompt "Username is mandatory:";
$plaintext[0]=~ s/^\s*(.*?)\s*$/$1/;
}
while($plaintext[1] =~ /^\s*$/){
$plaintext[1]= prompt "Password is mandatory:";
$plaintext[1]=~ s/^\s*(.*?)\s*$/$1/;
}
$ciphertext[0] = $cipher->encrypt($plaintext[0]);
$ciphertext[1] = $cipher->encrypt($plaintext[1]);
print $file $ciphertext[0];
print $file $ciphertext[1];
close $file;
open ( $file, '<', $file_name)
}
my @holder;
my $content;
if (open( $file, '<', $file_name)) {
local $/;
$content = <$file>;
} else {
warn "Could not open file '$filename' $!";
}
@holder = split(/(?=Salted__)/, $content);
print "Encrypted username:",$holder[0];
print "\n";
print "Encrypted password:",$holder[1],"\n";
$plaintext[0] = $cipher->decrypt( $holder[0] );
$plaintext[1] = $cipher->decrypt( $holder[1] );
print "\n\n";
print 'Username is:',"$plaintext[0]\n";
print 'Password is:',"$plaintext[1]\n";
close $file;
source
share