in reply to Using Cypher::CBC to encrypt fields in a file - Need Monk Help

And this shows how to abstract reading [CST]SV files and keep sane:

#!/usr/bin/perl use strict; use warnings; use Crypt::CBC; use Text::CSV; use Data::Dumper; my $type = "en"; my $key = "12345"; my $file = "data.txt.encrypt"; my $DEBUG = 1; print "type is $type, key is $key, file is $file\n" if $DEBUG; my $cipher = Crypt::CBC->new( -key => $key, -cipher => 'Blowfish' ); my $data = Text::CSV::csv( in => $file, sep_char => ' ', headers => 'auto', keep_headers => \my @headers ); if( ! $data ){ print STDERR "$0 : call to Text::CSV::csv() has failed +for input file '$file'.\n"; exit(1) } print Dumper($data) if $DEBUG; my ($outfile, $cipher_coderef); if( $type =~ /^en(crypt)?$/ ){ $cipher_coderef = sub { return $cipher->encrypt($_[0]) }; ($outfile = $file) =~ s/encrypt/decrypt/; } else { $cipher_coderef = sub { return $cipher->decrypt($_[0]) }; ($outfile = $file) =~ s/decrypt/encrypt/; } my @columns_to_encrypt = ('customerid', 'age'); my $rid = 0; foreach my $row (@$data){ $rid++; foreach my $colname (@columns_to_encrypt){ print "$0 : row $rid, column '$colname' : processing ...\n"; $row->{$colname} = $cipher_coderef->($row->{$colname}); } } if( ! Text::CSV_XS::csv( in => $data, sep_char => ' ', headers => \@headers, out => $outfile ) ){ print STDERR "$0 : call to Text::CSV_XS::csv() has failed.\n"; ex +it(1) } print "$0 : success, output in '$outfile'.\n";

Replies are listed 'Best First'.
Re^2: Using Cypher::CBC to encrypt fields in a file - Need Monk Help
by talexb (Chancellor) on Feb 21, 2019 at 19:54 UTC

    Very nicely done .. you caught my mistake about assuming that it was a CSV file, when in fact it was space delimited. You also set up a coderef for the encryption/decryption step, which is something that occurred to me, but decided against in order to get an example solution done quickly. And Text::CSV is a great module.

    Alex / talexb / Toronto

    Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.

      quite proud of my coderefs actually, thanks talexb