PHPで暗号化されたzipアーカイブを作成する 質問する

PHPで暗号化されたzipアーカイブを作成する 質問する

.txt ファイルを zip に暗号化する方法を探していますが、パスワードで保護された安全な方法で暗号化する必要があります。私の目標は、添付ファイルの内容を誰にも読まれないように、このファイルを電子メールで送信することです。

これを実現する簡単で、何よりも安全な方法を誰か知っていますか? zip アーカイブを作成することはできますが、それを暗号化する方法や、これがどれほど安全であるかはわかりません。

ベストアンサー1

PHP 7.2(1時間前にリリース)では、これを実行する正しい方法は、ZipアーカイブネイティブPHPコード。(感謝アブラハム・トゥガロフこの変化がやってくることを指摘してくれたことに対して

簡単な答えは次のようになります。

<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
    $zip->setPassword('secret_used_as_default_for_all_files'); //set default password

    $zip->addFile('thing1.txt'); //add file
    $zip->setEncryptionName('thing1.txt', ZipArchive::EM_AES_256); //encrypt it

    $zip->addFile('thing2.txt'); //add file
    $zip->setEncryptionName('thing2.txt', ZipArchive::EM_AES_256); //encrypt it

    $zip->close();

    echo "Added thing1 and thing2 with the same password\n";
} else {
    echo "KO\n";
}
?>

しかし、名前ではなくインデックスで暗号化方式を設定することもできますし、ファイルごとにパスワードを設定することもできます。また、より弱い暗号化オプションを指定するには、新しくサポートされた暗号化オプション。

この例では、より複雑なオプションを実行します。

<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) { 
     //being here means that we were able to create the file..

     //setting this means that we do not need to pass in a password to every file, this will be the default
    $zip->addFile('thing3.txt');

    //$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_128);
    //$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_192);
    //you should just use ZipArchive::EM_AES_256 unless you have super-good reason why not. 
    $zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_256, 'password_for_thing3');

     $zip->addFile('thing4.txt');
    //or you can also use the index (starting at 0) of the file...
    //which means the following line should do the same thing...
    //but just referencing the text.txt by index instead of name..
    //$zip->setEncryptionIndex(1, ZipArchive::EM_AES_256, 'password_for_thing_4'); //encrypt thing4, using its index instead of its name...

    $zip->close();
    echo "Added thing3 and thing4 with two different passwords\n";
} else {
    echo "KO\n";
}
?>

libzip 1.2.0 で暗号化のサポートが導入されたため、zip 暗号化の基盤サポートが有効になりました。したがって、このコードを実行するには、php 7.2 と libzip 7.2 が必要です... このメモが「すぐに」この回答の cruft になることを願っています。

おすすめ記事