Reputation: 311
I'm working on a simple Zend application and I need to encrypt all the financial figures before storing them in the database, and decrypt them when needed. I used mcrypt_encrypt()
and mcrypt_decrypt()
. As I need to decrypt the figures I used a constant initialization vector(iv), which is not at all recommended.
here is my code:
define ('string','WdryhedeescmsfkirYNemsjdesapQ');
define ('iv', '$356?dWuSkm)@g%dnw#8mA*');
class FormatValues {
const string= 'WdryhedeescmsfkirYNemsjdesapQ';
const iv = '$356?dWuSkm)@g%dnw#8mA*';
public function encrypt($val){
$enc = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $val,self::string , MCRYPT_MODE_CBC,self::iv);
return $enc;
}
public function decrypt($val){
$dec = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $val,self::string , MCRYPT_MODE_CBC,self::iv), "\0");
return $dec;
}
}
The encrypt()
method encrypts the data, but when decrypting, it doesn't give the correct figure.
Why is this? Is there some other way to encrypt and decrypt data without having a constant iv?
Thanks in advance
Charu
Upvotes: 0
Views: 5640
Reputation: 9269
I use something like that for my project, try it !
$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
echo 'Encrypted:' . "\n";
var_dump($encrypted);
echo "\n";
echo 'Decrypted:' . "\n";
var_dump($decrypted); // spaces are preserved
Upvotes: 4
Reputation: 799
Don't know if it's the correct answer but, you should definitely not define a constant called string
as it is a reserved keyword in PHP.
Upvotes: 0