Perl Crypt:CBC encrypts/decrypts 仅第一个列表

Perl Crypt:CBC encrypts/decrypts only first list

这是我的代码:

#!/usr/bin/perl -w
use Crypt::CBC;

my $scriptkey = qx(cat /tmp/scriptkeyfile);
chomp $scriptkey;

print new Crypt::CBC(-key=>"$scriptkey",-salt=>"my_salt")->encrypt(qx(cat $ARGV[0]));

此脚本只加密给定文件的第一行。如果我将加密更改为解密,它只会解密给定文件的一行。如何更改此设置以加密整个文件。

Crypt::CBC docs actually explain如何加密整个文件。

The CBC algorithm must buffer data blocks internally until they are even multiples of the encryption algorithm's blocksize (typically 8 bytes). After the last call to crypt() you should call finish(). This flushes the internal buffer and returns any leftover ciphertext.

In a typical application you will read the plaintext from a file or input stream and write the result to standard output in a loop that might look like this:

   $cipher = new Crypt::CBC('hey jude!');
   $cipher->start('encrypting');
   print $cipher->crypt($_) while <>;
   print $cipher->finish();

因此您的程序可能如下所示。

use strict;
use warnings;
use Crypt::CBC;
use File::Slurp;

my $scriptkey = read_file( '/tmp/scriptkeyfile' );
chomp $scriptkey;

open my $fh, '<', $ARGV[0] or die $!; # sanitize this!!!

my $encrypted;
my $cipher = Crypt::CBC->new( -key => $scriptkey, -salt => "my_salt" );
$cipher->start('encrypting');
$encrypted .= $cipher->crypt($_) while <$fh>;
$encrypted .= $cipher->finish;

close $fh;

qx 是列表上下文 return 是一个行列表,所以

->encrypt(qx( ... ))

结果

->encrypt($line1, $line2, $line3, ...)

但是

->encrypt($plaintext)

符合预期。在标量上下文中使用 qx 将整个输出 return 作为一个标量。

my $file = qx( prog ... );
die("Can't execute prog: $!\n") if $? == -1;
die("prog killed by signal ".( $? & 0x7F )."\n") if $? & 0x7F;
die("prog exited with error ".( $? >> 8 )."\n") if $? >> 8;

my $cypher = Crypt::CBC->new( ... );
print $cypher->encrypt($file);

我假设你实际上没有使用 cat,这只是一个例子。