mitch_au
mitch_au

Reputation: 323

PHP encryption/decryption from text file

this really has me stumped....

I'm messing around with encryption using PHP.

Using memory, everything is fine....

//encrypt the sensitive data
$encryptedData = encrypt($senstiveData, $theKey);

//decrypt the data
$decryptedData = decrypt($encryptedData, $theKey);

//print decrypted string
echo "<br>Decrypted String:" . $decryptedData;

i.e. the decrypted string: contains the correct value.

However, if I write the information out to file.. it breaks.

$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>";

And... the answer is incorrect.

I've verified that the key and array used in both versions are identical (i.e. the reconstructed unserialized array contains the same values as before it was serialized), could something be getting lost in translation when I write to file?

Any ideas where I should start looking to debug this?

Any advice would be appreciated, Mitch.

Upvotes: 2

Views: 2116

Answers (1)

Marc
Marc

Reputation: 11613

Remove the new-line character(s) from your fwrite(). I.e., don't do this:

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

The \n can screw up the encryption/decryption routines.

This should be adequate:

fwrite($fh, $keyCode);

Upvotes: 3

Related Questions