Dig*_*its 22 php encryption zip
我正在寻找一种方法将.txt文件加密成zip,但是采用安全的密码保护方式.我的目标是通过电子邮件发送此文件给我,没有人能够阅读附件的内容.
有没有人知道一个简单的,最重要的,安全的方法来实现这一目标?我可以创建zip存档,但我不知道如何加密它们,或者它是多么安全.
fro*_*ega 18
注意:此答案建议使用已知不安全的加密方法,即使密码正确也是如此.请参阅评论链接 和AES上的Winzip QA.使用php 7.2(和libzip 1.2.0)支持in-php AES zip加密,这意味着这个答案很快就会过时.在此之前,请参阅此答案,了解如何调用7z而不是zip命令,该命令支持winzip的AES加密.
你可以用这个:
<?php echo system('zip -P pass file.zip file.txt'); ?>
Run Code Online (Sandbox Code Playgroud)
pass是密码,file.txt将压缩成file.zip.这应该适用于Windows和Linux,你只需要为Windows获得一个免费的zip版本(http://www.info-zip.org/Zip.html#Win32)
这种安全性可以通过暴力攻击,字典攻击等来打破.但这并不容易,特别是如果你选择了长而难以猜测的密码.
ftr*_*ter 12
从PHP 7.2(一小时前发布)开始,正确的方法是使用ZipArchive本机php代码中包含的其他功能.(感谢abraham-tugalov指出这一变化即将到来)
现在简单的答案看起来像这样:
<?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";
}
?>
Run Code Online (Sandbox Code Playgroud)
但您也可以按索引而不是名称设置加密方法,并且可以基于每个文件设置每个密码...以及使用新支持的加密选项指定较弱的加密选项.
此示例练习这些更复杂的选项.
<?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";
}
?>
Run Code Online (Sandbox Code Playgroud)
由于libzip 1.2.0引入了对加密的支持,因此启用了对zip加密的底层支持.所以你需要有php 7.2和libzip 7.2才能运行这段代码...希望这个说明将在这个答案"真的很快"