Perl Blowfish/CBC加密和解密函数



这里是Perl和密码学的新手。有人有任何简单的加密/解密函数(使用Blowfish或CBC(来封装所有的幕后肮脏工作吗?我想要一个固定的密钥来使用,并且能够传递任意长度的字符串进行加密。

为了清楚起见,我想使用encrypt函数加密凭据,将结果保存在某个位置,并在需要时解密。。。同时使用相同的密钥。

我基本上想这样做:

$fixedKey = "0123456789ABCDEF";
$plainText = "A string of any length..........";
$encryptedString = Encrypt($fixedKey, $plainText); 
$retrievedText = Decrypt($fixedKey, $encryptedString);

非常感谢。

以下使用Crypt::CBC进行盐析、填充和链接,并使用Crypt::Rijndael(AES(进行加密。

use strict;
use warnings;
use feature qw( say );
use Crypt::CBC qw( );
sub encrypt {
my ($key, $plaintext) = @_;
my $iv = Crypt::CBC->random_bytes(16);
my $cipher = Crypt::CBC->new(
-cipher      => 'Rijndael',
-literal_key => 1,
-key         => $key,
-iv          => $iv,
-header      => 'none',
);
return $iv . $cipher->encrypt($plaintext);
}
sub decrypt {
my ($key, $ciphertext) = @_;
my $iv = substr($ciphertext, 0, 16, '');
my $cipher = Crypt::CBC->new(
-cipher      => 'Rijndael',
-literal_key => 1,
-key         => $key,
-iv          => $iv,
-header      => 'none',
);
return $cipher->decrypt($ciphertext);
}
{
my $key = Crypt::CBC->random_bytes(32);
say "Key: ", unpack "H*", $key;
my $expect = 'secret';
say "Plaintext: $expect";
my $ciphertext = encrypt($key, $expect);
say "Ciphertext: ", unpack "H*", $ciphertext;
my $got = decrypt($key, $ciphertext);
say "Plaintext: $got";
say $expect eq $got ? "ok" : "not ok";
}

最新更新