Encrypting/decrypting passwords in plain-text files
Posted on 2007-03-18
I have a settings file for my website which contains an array with important settings, and I want to have several of the values encrypted from plain view and then decrypted when I need to use them (e.g. the passwords to access databases etc.). I've never used the Mcrypt functions in PHP, so I've been trying a small test where I encrypt a variable (entered into a form) which is then encrpyted and written to a file on my server, and then decrypt the variable written to the file. My problem is that when I decrypt the variable, it is not the same as I originally entered.
$fp = fopen('./file.php', 'w');
fwrite($fp, "<?php\n\n\$variable = '" . mcrypt_encrypt(MCRYPT_RIJNDAEL_256, mhash(MHASH_MD5, 'tirg412e1dw'), $_POST['variable'], MCRYPT_MODE_CBC, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND)) . "';\n\n?>");
echo '<p>$variable = ' . mcrypt_decrypt(MCRYPT_RIJNDAEL_256, mhash(MHASH_MD5, 'tirg412e1dw'), $variable, MCRYPT_MODE_CBC, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND)) . '.</p>';
I'm assuming that its a problem with the cipher, mode or IV, but I was also wondering if it was a problem that I'm writing it to a file and the character codes were somehow being lost.
Thanks for any help, Adam.