end0tknr's kipple - web写経開発

太宰府天満宮の狛犬って、妙にカワイイ

パスワード(暗号化)非対応なArchive::Zipは /usr/bin/zip, unzipで代用

Archive::Zipはパスワード(暗号化)に非対応

perlでzipファイルを扱う際、Archive::Zipを用いていましたが、パスワード(暗号化)に対応していないとは知りませんでした。

http://search.cpan.org/perldoc?Archive::Zip

isEncrypted()
  Return true if this member is encrypted.
  The Archive::Zip module does not currently create
  or extract encrypted members.

zip -eで暗号化zipを作成し、unzip -Pで暗号化zipを展開

次のサンプルスクリプトは、test fileを暗号化zip後、その暗号化zipファイルを展開するものです。

#!/usr/local/bin/perl
use strict;
use warnings;
use Data::Dumper;

my $ZIP_CMD = "/usr/bin/zip";
my $UNZIP_CMD = "/usr/bin/unzip";
my $ZIP_PASSWD = "hogehoge";

sub main {
    my ($file_path) = @_;
    my $zip_path = zip($file_path);	#暗号化zipの作成
    my $content = unzip($zip_path);	#暗号化zipの展開
    print Dumper($content);
}

sub zip {
    my ($file_path) = @_;
    my $zip_path = "$file_path.zip"; #作成するzip file
    #暗号化zip(-e)の作成
    my $cmd = "$ZIP_CMD -P $ZIP_PASSWD -e $zip_path $file_path";
    my $ret = system($cmd);
    return undef if ($ret != 0); #zip file作成失敗
    return $zip_path;
}

sub unzip {
    my ($zip_path) = @_;
    #暗号化zipを展開(-P)し、パイプ(-p)で渡します
    my $cmd = "$UNZIP_CMD -p -P $ZIP_PASSWD $zip_path |";
    open my $fh,$cmd or die "can't open $cmd :$!";
    my @lines = <$fh>;
    close $fh or die "can't close $cmd:$!";
    return \@lines;
}
main(@ARGV);

test file

This is zip/unzip test file.

実行結果

[endo@colinux perl]$ ./foo.pl text.txt 
  adding: text.txt (deflated 3%)
$VAR1 = [
          'This is zip/unzip test file.
'
        ];