我已经看到了从命令行使用openssl_encrypt
加密文件的解决方案,如下所示:
file_put_contents ('./file.encrypted',openssl_encrypt ($source, $method, $pass, true, $iv));
$exec = "openssl enc -".$method." -d -in file.encrypted -nosalt -nopad -K ".strtohex($pass)." -iv ".strtohex($iv);
或者,使用 openssl_encrypt
加密字符串,如下所示:
$string = 'It works ? Or not it works ?';
$pass = '1234';
$method = 'aes128';
file_put_contents ('./file.encrypted', openssl_encrypt ($string, $method, $pass));
但不是直接从代码加密文件的东西。为什么?
如果我想从代码中加密 2-10mb 文件,而不是像使用命令行那样为每个文件打开单独的进程怎么办?
我正在寻找可以为我做到这一点的代码示例,例如:
$myfile = 'files/myfile.doc';
$pass = '1234';
$method = 'aes128';
file_put_contents ('./file.encrypted', openssl_encrypt ($myfile, $method, $pass));
谢谢
没有理由不能使用 file_get_contents()
将文件读入变量,使用 openssl_public_encrypt() 加密文件,然后使用 fopen() fwrite() 和 fclose() 将其保存到磁盘,但使用这种方法可以加载到内存中的文件大小可能有限制。
在脚本中执行文件加密也可能会产生性能开销,但您应该能够足够轻松地对此进行测试。