从文本文件进行 PHP 加密/解密


PHP encryption/decryption from text file

这真的让我难倒了....

我正在使用PHP进行加密。

使用内存,一切都很好。

//encrypt the sensitive data
$encryptedData = encrypt($senstiveData, $theKey);
//decrypt the data
$decryptedData = decrypt($encryptedData, $theKey);
//print decrypted string
echo "<br>Decrypted String:" . $decryptedData;

即解密的字符串:包含正确的值。

但是,如果我把信息写到文件中......它会中断。

$orderFile = "orders.dat";
$fh = fopen($orderFile, 'a') or die("can't open file");
fwrite($fh, $keyCode . "'n");
$serializedArray = serialize($encryptedData); 
fwrite($fh, $serializedArray . "'n");
fclose($fh);

$file = fopen("orders.dat","r");
//key is first line in 'orders.dat'
$theKey = fgets($file);
//serialised array is second line...
$unserializedArray = unserialize(fgets($file));
$decryptedData2 = decrypt($unserializedArray, $theKey);
//print decrypted string
echo "<br>Decrypted String:" . $decryptedData2 . "<br>";

而且......答案是不正确的。

我已经验证了两个版本中使用的键和数组是相同的(即重建的未序列化数组包含与序列化之前相同的值),当我写入文件时,翻译中会不会丢失某些内容?

有什么想法,我应该从哪里开始调试它?

任何建议将不胜感激,米奇。

fwrite()中删除换行符。 即,不要这样做:

fwrite($fh, $keyCode . "'n");

'n可能会搞砸加密/解密例程。

这应该足够了:

fwrite($fh, $keyCode);