I wrote the code you need.
Some utility functions
sub read_bytes { my ($fh, $to_read) = @_; my $buf = ''; while ($to_read) { my $bytes_read = read($fh, $buf, $to_read, length($buf)); die("$!\n") if !defined($bytes_read); die("Unexpected end of file\n") if !$bytes_read; $to_read -= $bytes_read; } return $buf; } sub read_uint32 { my ($fh) = @_; return (unpack('N', read_bytes($fh, 4))); } sub read_str { my ($fh) = @_; my $length = read_uint32($fh); return read_bytes($fh, $length); } sub write_uint32 { my ($fh, $n) = @_; print $fh (pack('N', $n)); } sub write_str { my ($fh, $str) = @_; print $fh (pack('N', length($str)), $str); }
The line-by-line encrypter:
sub writeSubmissions { my ($cipher, $log_file, $str) = @_; open(my $FH_encrypted, '>>', $log_file) or die; binmode $FH_encrypted; flock $FH_encrypted, LOCK_EX; write_str($FH_encrypted, $cipher->encrypt($str)); } my $key_file = 'key_file.txt'; my $act_log_file = "pem.enc"; my $pem_log_file = "act_encrypted.enc"; my $my_key = `openssl enc -bf-cbc -d -in \Q$key_file\E -k encrypt`; my $cipher = Crypt::CBC->new({ key => $my_key, cipher => 'Rijndael' }) +; writeSubmissions($cipher, ..., ...);
The line-by-line decrypter:
my $key_file = 'key_file.txt'; my $encrypted = '...'; my $decrypted = '...'; my $my_key = `openssl enc -bf-cbc -d -in \Q$key_file\E -k encrypt`; my $cipher = Crypt::CBC->new({ key => $my_key, cipher => 'Rijndael' }) +; open(my $FH_decrypted, '>', $decrypted) or die("Unable to create decrypted file \"$decrypted\": $!\n"); binmode $FH_decrypted; flock $FH_decrypted, LOCK_EX; open(my $FH_encrypted, '<', $encrypted) or die("Unable to open encrypted file \"$encrypted\": $!\n"); binmode $FH_encrypted; flock $FH_encrypted, LOCK_SH; while (!eof($FH_encrypted)) { print $FH_decrypted $cipher->decrypt(read_str($FH_encrypted)); }
Update: Fixed bugs mentioned in replies.
Update: Tested (minus the openssl bit). Fixed other bugs.
In reply to Re^3: line by line Encryption fun with Crypt::CBC and Rijndael? File Ownership issues? (code)
by ikegami
in thread line by line Encryption fun with Crypt::CBC and Rijndael? File Ownership issues?
by hmbscully
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |