繁体   English   中英

使用phpseclib的Crypt_AES类立即加密和解密文件使文件为空

[英]Use phpseclib's Crypt_AES class to encrypt and decrypt a file at once makes the file empty

因此,我有一个脚本,该脚本使用phpseclib一次对同一文件进行加密和解密。 我要做的是读取文件中的内容并对其进行加密,然后将其写回到同一文件中。 然后,我再次读取该文件以获取加密内容并将其解密,然后将解密后的内容再次写回到同一文件中。

我期望原始文件最后保持不变。 不知何故,当在第二步解密加密的内容时,解密的内容变为空。 下面是示例代码:

$aes = new Crypt_AES();

$aes->setKey('abcdefghijklmnop');

$filename = "testfile.txt";

$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$contents = $aes->encrypt($contents);

$handle = fopen($filename, 'w');
fwrite($handle, $contents);
fclose($handle);

$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
$contents = $aes->decrypt($contents);
// I checked out the error_log, the contents became empty here. 
// Shouldn't it be recovered into original content?

$handle = fopen($filename, 'w');
fwrite($handle, $contents);
fclose($handle);

奇怪的是,如果我将脚本分为两个步骤,然后先运行第一步,然后再运行第二步,那么一切都像灵符一样运作。

我知道这个工作流程有点尴尬,我可以通过在进行第一次读取时存储原始内容并将其用于以后的写回操作来绕过此问题。 只是好奇我在这里做错了什么? 谢谢

问题在于您正在执行多个filesize()调用。 完成第一个操作后,将缓存大小。 然后,写文件,然后执行filesize()一次就可以了filesize()将返回它所返回即使自上一次运行(由于PKCS填充)文件大小已经改变最后一次。 演示:

<?php
file_put_contents('demo.txt', 'zzz');
echo filesize('demo.txt') . "\r\n";
file_put_contents('demo.txt', 'zzzzzz');
echo filesize('demo.txt');

您可能希望返回3和6,对吗? 对我来说,它返回3和3。

我建议使用file_get_contents()file_put_contents() 如果必须使用fopen和fgets,则在每个filesize()调用之后也进行clearstatcache()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM