Question

I am using a text

const ENCRYPTION_KEY = '3aa22e01c04c7059778c54d122b0273689fba00f4a166a66d15f7ba6a8ba8743';
$str = "1844427316My Name Is Dave1336407610774000000000000";

function  encrypt($str){
trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,ENCRYPTION_KEY, $str,MCRYPT_MODE_CBC,mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),MCRYPT_RAND))));
}

function decrypt($encryptedtext){
return trim(
        mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128, 
            ENCRYPTION_KEY, 
            base64_decode($encryptedtext), 
            MCRYPT_MODE_CBC,
            mcrypt_create_iv(
                mcrypt_get_iv_size(
                    MCRYPT_RIJNDAEL_128,
                    MCRYPT_MODE_CBC
                ), 
                MCRYPT_RAND
            )
        )
        );
}

But whenever I refresh the page calling these function with values mentioned above, I get different values encryption, but in decryption, the initial decrypted value changes everytime but rest gets decrypted correctly like wise:

F7…Ÿ{4©eŠQ9­t¤e Is Dave1336407610774000000000000

I have also refered the SIMILAR QUESTION and used the "iv" function in decryption as well as answered in it

Could some one guide me whats getting wrong in here?

Was it helpful?

Solution

It was thoughtful But I found the Solution:

While decrypting, I used the same IV and key as when encrypting.

My encrypt function needs to return the IV as well as the encrypted data. That IV is sent to the decrypt function with the data and the key.

See the below Change in Code with complete 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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top