0

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

4

2 回答 2

4

我在我的项目中使用了类似的东西,试试吧!

$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
于 2012-07-18T09:53:31.673 回答
0

不知道这是否是正确的答案,但是,您绝对不应该定义一个名为的常量string,因为它是 PHP 中的保留关键字。

于 2012-07-18T09:51:06.010 回答