Padyster
Padyster

Reputation: 1003

PHP MYCRYPT - RIJNDAEL_128 with Mcrypt CBC gives the different encryption string everytime

I am back again with a PHP+RIJNDAEl_128+CBC.

I am successful in encryption and decryption to the raw string.

But the only problem I am facing is I get the DIFFERENT ENCRYPTION string every time.

Which I believe should be same every time ideally.

Below is the code:

class Encypt{

const ENCRYPTION_KEY = '3aa22e01c04c7059778c54d122b0273689fba00f4a166a66d15f7ba6a8ba8743';


function createQueryString(){
$str = "1844427316My Name Is Dave1336407610774000000000000";
$encStr = $this->encrypt($str);

return $encStr;
}

function encrypt($strValue){
$iv =mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),MCRYPT_RAND);
$encData = trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,self::ENCRYPTION_KEY, $strValue,MCRYPT_MODE_CBC,$iv)));
            $data['iv'] = $iv;
            $data['encdata'] = $encData;

            return $data;
}
 /**
     *  Function to decrypt data using AES Encryption Symmetric Algorithm 128 bytes
     */
    function decrypt($strValue, $iv){
            return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128,ENCRYPTION_KEY,base64_decode($strValue),MCRYPT_MODE_CBC,$iv));
    }

}    
$enc_obj = new Encypt();

$encstr = $enc_obj->createQueryString();

echo "Encrypted Str:-->".$encstr['encdata']."<br>";
$deCrypt = $enc_obj->decrypt($encstr['encdata'], $encstr['iv']);
echo "Decrypted Str:-->".$deCrypt;

Upvotes: 1

Views: 923

Answers (2)

Alexandre Danault
Alexandre Danault

Reputation: 8672

The different values you receive each time for the encrypted text is normal regarding the different IVs in every run. This is actually part of the algorithm, and makes it more secure.

Upvotes: 2

Sagar Ranglani
Sagar Ranglani

Reputation: 5691

Your encrypt function has a call to mcrypt_create_iv(<<iv_size>>, MCRYPT_RAND);

Since the call has MCRYPT_RAND(system random number generator) as the source, a new Initialization Vector created every-time will be different from previous ones.

This will result in different encrypted string every-time. You can decrypt the cypher-text using the same Initialization Vector as used in encryption process.

Upvotes: 1

Related Questions