Perl Blowfish/CBC 加密和解密函数
Perl Blowfish/CBC Encryption and Decryption functions
这里是 Perl 和密码学的新手。有没有人有任何简单的 Encrypt/Decrypt 函数(使用 Blowfish 或 CBC)来封装所有底层脏工作?我想要一个 fixed KEY 来使用并能够传递一个 any 长度的字符串进行加密。
为清楚起见,我想使用 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";
}
这里是 Perl 和密码学的新手。有没有人有任何简单的 Encrypt/Decrypt 函数(使用 Blowfish 或 CBC)来封装所有底层脏工作?我想要一个 fixed KEY 来使用并能够传递一个 any 长度的字符串进行加密。
为清楚起见,我想使用 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";
}