これは、上記のコードの一部と Perlmonk から取得した一部を利用した本格的なコードです。スクリプトは、最初にユーザーにユーザー名とパスワードを尋ね、それを暗号化して .crypt ファイルに保存します。次に、それを読み取り、復号化して元のテキストを表示します。2 回目は、既存のユーザー資格情報を使用します。
use Crypt::Rijndael;
use IO::Prompter;
use Crypt::CBC;
#keys
my $key = "a" x 32;
my $cipher = Crypt::CBC->new( -cipher => 'Rijndael', -key => $key );
my @plaintext;
my @ciphertext;
#keys
#filefield
#password file name
#my $file_name = ".crypt";
my $file_name = ".crypt";
#File Handler
my $file;
#If we cannot open the password file we initiate a new one
unless ( open ( $file, '<:encoding(UTF-8)', $file_name) ) { #<:encoding(UTF-8)
#Create a new file in write mode
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]);
#we save the password in a file
print $file $ciphertext[0];
#print $file "\n";
#we save the password in a file
print $file $ciphertext[1];
#we close the file ( Writing mode )
close $file;
#Reopen the file in reading mode
open ( $file, '<', $file_name)
}
my @holder;
my $content;
if (open( $file, '<', $file_name)) {
#chomp(@holder = <$file>);
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";
#Loading the password en decrypt it
$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 the file
close $file;
#filefield