简体   繁体   English

PHP MYCRYPT - RIJNDAEL_128与Mcrypt CBC每次都提供不同的加密字符串

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

I am back again with a PHP+RIJNDAEl_128+CBC. 我又回来了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. 但我遇到的唯一问题是每次都会得到不同的ENCRYPTION字符串。

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;

The different values you receive each time for the encrypted text is normal regarding the different IVs in every run. 对于加密文本,每次收到的不同值对于每次运行中的不同IV都是正常的。 This is actually part of the algorithm, and makes it more secure. 这实际上是算法的一部分,并使其更安全。

Your encrypt function has a call to mcrypt_create_iv(<<iv_size>>, MCRYPT_RAND); 您的加密函数调用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. 由于调用具有MCRYPT_RAND (系统随机数生成器)作为源,因此每次创建的新初始化向量将与先前的不同。

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. 您可以使用加密过程中使用的相同初始化向量来解密密文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM