perl@RijndaelでAES暗号化したファイルをphpでザオリク。
ちょいと苦労したので備忘録。。
---perl-----------------------------------------------------------------
#!/usr/bin/perl
use strict;
use Crypt::CBC;
# 暗号化したい文書
my $crypttext = "ざんねん!!わたしのぼうけんはこれでおわってしまった!!";
# 暗号化の鍵
my $cryptedkey = "シャドウゲイト";
# オブジェクトの作成
my $crypter = Crypt::CBC->new({ 'key' => $cryptedkey,
'cipher' => 'Rijndael',
'iv' => '1234567890123456',
'literal_key' => 0,
'padding' => 'null',
'prepend_iv' => 0
});
# 暗号化
my $cryptedtext = $crypter->encrypt($crypttext);
# ファイルに保存
open(FILE ,">/tmp/shadowgate.dead");
print FILE $cryptedtext;
close(FILE);
exit;
========================================================================
で、これをphpで復元してみる。。
---php------------------------------------------------------------------
$this->ks = 32;
$this->data ="";
$this->pass = "シャドウゲイト";
$this->iv = '1234567890123456';
$this->td = mcrypt_module_open('rijndael-128', '', 'cbc', '');
$material = md5($this->pass, true);
while (strlen($material) < $this->ks) {
$material .= md5($material, true);
}
$this->key = substr($material,0,$this->ks);
$lines = file('/tmp/shadowgate.dead');
foreach($lines as $key=>$value){
$this->data.=$value;
}
mcrypt_generic_init($this->td, $this->key, $this->iv);
$dec_data = mdecrypt_generic($this->td, $this->data);
// 終了処理
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
print $dec_data;
?>
========================================================================
phpはモジュールが色々やってくれるわけじゃないので最初わかんなかった。
perlのCBC.pmを読む羽目になりますた。
特にperlはkeyの長さが合わなくても勝手にやってくれるけど、phpは自炊。。orz
逆はそのまま逆の処理をすればphp→perlに出来るはずです。