Perl Blowfish / CBC加密和解密功能

时间:2018-12-11 17:28:45

标签: perl encryption blowfish

这里是Perl和密码学的新手。是否有人拥有任何简单的加密/解密功能(使用Blowfish或CBC)来封装所有引擎盖下的肮脏工作?我想使用一个固定的密钥,并能够传递长度为任何的字符串进行加密。

为清楚起见,我想使用Encrypt函数对凭据进行加密,将结果保存在某个地方,然后在需要时对其进行解密...始终使用相同的密钥。

我基本上想这样做:

$fixedKey = "0123456789ABCDEF";
$plainText = "A string of any length..........";

$encryptedString = Encrypt($fixedKey, $plainText); 

$retrievedText = Decrypt($fixedKey, $encryptedString);

感激。

1 个答案:

答案 0 :(得分:1)

以下使用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";
}