Search code examples
perlcryptcbc-mode

Perl Crypt:CBC encrypts/decrypts only first list


Here is my code:

#!/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]));

This script only encrypts first line of given file. If I change encrypt to decrypt, it will only decrypt one line of given file. How to change this, to crypt whole file.


Solution

  • qx is list context returns a list of lines, so

    ->encrypt(qx( ... ))
    

    results in

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

    but

    ->encrypt($plaintext)
    

    is expected. Use qx in scalar context to return the entire output as one scalar.

    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);
    

    I'm assuming you aren't actually using cat, that it's just an example.