2

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.

2
  • I use encryption as well but I was't aware that there are PHP functions decrypt/encrypt. The functions I know and use are part of the mcrypt module and starts with mcrypt_ (e.g. mcrypt_decrypt). Commented Apr 29, 2012 at 4:37
  • 1
    Why are you using a \n in your fwrite function? Hard returns are extra bytes, which might throw off your encryption functions. Commented Apr 29, 2012 at 4:38

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help Marc, I wasted 5 hours trying to figure that out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.