proper PHP mcrypt encryption methods?

前端 未结 2 2041
轮回少年
轮回少年 2021-01-03 04:38

Ok, I have tried to create my own encryption/decryption methods using PHP mcrypt, and when I posted them a while back some called them \"trash\". They were ment

2条回答
  •  清酒与你
    2021-01-03 05:27

    You can create an iv with mcrypt_create_iv(), using the appropriate size for your encryption mode.

    $size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_192, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($size, MCRYPT_DEV_RANDOM);
    

    Then pass it to mcrypt_cbc() as the optional 5th parameter. The only changes I've made here to your original functions are to pass in $iv:

    function encrypt($key, $data, $iv){
        $encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $data, MCRYPT_ENCRYPT, $iv);
        return base64_encode($encrypted_data);
    }
    
    function decrypt($key, $encryptedData, $iv){
        $dec = base64_decode($encryptedData);
        $decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $dec, MCRYPT_DECRYPT, $iv);
        return trim($decrypt);
    }
    

提交回复
热议问题