Page 1 of 1

writing out encrypted file is different

Posted: Sun Jul 06, 2008 12:42 pm
by marche
hi guys,
i trying to read in a file, encrypt it and write it out but i cant decrypt it to be the same file. After i check i found that the encrypted value is different from what i wrote out tats why it failed to decrypt correctly.

My Code
<?php
/*--------------Encrypt and write to new file ---------------*/
$filename = "test.jpg";
$fp=fopen($filename,"rb");
$file=fread($fp,filesize($filename));

echo "Original File: <br>".$file."<br /><br />";
$key = "dab94f925b350349ad6b67b68def954b";

$encrypted = mcrypt_cbc(MCRYPT_RIJNDAEL_128,substr($key,0,32) ,$file,MCRYPT_ENCRYPT,substr($key,32,16));
echo "Encrypted: <br>".$encrypted."<br /><br />";

$enFile = "testE.jpg";
$Handle = fopen($enFile, 'w');
fwrite($Handle, $encrypted);
fclose($Handle);

/*--------------END of Encrypt and write to new file ---------------*/

/*--------------Decrypt and write to new file ---------------*/
$enfile = file_get_contents ("testE.jpg");

echo "Read Decrypted File: <br>".$enfile."<br /><br />";
echo "Encrypted File look like: <br>".$enfile."<br /><br />";

$decrypted = trim(mcrypt_cbc(MCRYPT_RIJNDAEL_128,substr($key,0,32) ,$enfile,MCRYPT_DECRYPT,substr($key,32,16)));

$enFile = "testDec.jpg";
$Handle = fopen($enFile, 'w');

fwrite($Handle, $decrypted);
fclose($Handle);
/*--------------END of Encrypt and write to new file ---------------*/
?>
i noticed that some characters such as � were missing when i read back the encrypted file

Is there a proper way to write the binary to a file exactly
or am I doing something else wrong?
really appreciate any advise

Re: writing out encrypted file is different

Posted: Sun Jul 06, 2008 3:14 pm
by jaoudestudios
I wrote these functions last year, it is not the highest encryption as it is only ECB.

I have used them many times in the past and had no problem.

Hopefull they will help.

Encryption & Decryption link...
http://www.forum.jaoudestudios.com/view ... ?f=13&t=14

Re: writing out encrypted file is different

Posted: Tue Jul 08, 2008 2:12 pm
by marche
thank jaoudestudios
from what i learn from your code, i use the hextobin and bintohex to do the necessary translation when writing and reading from the files and it work fine with my code.
Appreciate your prompt reply

Re: writing out encrypted file is different

Posted: Wed Jul 09, 2008 2:05 am
by jaoudestudios
No problem :)