gpt4 book ai didi

php - 使用 PHP 创建一个加密的 zip 存档

转载 作者:IT王子 更新时间:2023-10-28 23:50:00 25 4
gpt4 key购买 nike

我正在寻找一种将 .txt 文件加密为 zip 的方法,但要以安全的密码保护方式进行。我的目标是将此文件通过电子邮件发送给我,而任何人都无法阅读附件的内容。

有没有人知道一个简单的,最重要的是,安全的方法来完成这个?我可以创建 zip 存档,但我不知道如何加密它们,或者,这有多安全。

最佳答案

从 php 7.2(一个小时前发布)开始,正确的方法是使用 ZipArchive 中包含的附加功能。 native 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";
}
?>

但是您也可以通过索引而不是名称来设置加密方法,并且可以在每个文件的基础上设置每个密码...以及指定较弱的加密选项,使用 newly supported encryption options.

这个例子练习了这些更复杂的选项。

<?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";
}
?>

启用了对 zip 加密的底层支持,因为 libzip 1.2.0 引入了对加密的支持。因此,您将需要 php 7.2 和 libzip 7.2 才能运行此代码...希望此说明“很快”就可以解决这个问题

关于php - 使用 PHP 创建一个加密的 zip 存档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/646195/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com