proper PHP mcrypt encryption methods?

前端 未结 2 2043
轮回少年
轮回少年 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:25

    Here is a snippet of the mcrypt functions I use. They use mcrypt_generic and mdecrypt_generic, which should be used according to the PHP manual.

    function encrypt($key, $data){
        $b = mcrypt_get_block_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
        $enc = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
        $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($enc), MCRYPT_DEV_URANDOM);
        mcrypt_generic_init($enc, md5($key), $iv);
    
        // PKCS7 Padding from: https://gist.github.com/1077723
        $dataPad = $b-(strlen($data)%$b);
        $data .= str_repeat(chr($dataPad), $dataPad);
    
        $encrypted_data = mcrypt_generic($enc, $data);
    
        mcrypt_generic_deinit($enc);
        mcrypt_module_close($enc);
    
        return array(
            'data' => base64_encode($encrypted_data),
            'iv' => base64_encode($iv)
        );
    }
    
    function decrypt($key, $iv, $encryptedData){
        $iv = base64_decode($iv);
        $enc = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CBC, '');
        mcrypt_generic_init($enc, md5($key), $iv);
    
        $encryptedData = base64_decode($encryptedData);
        $data = mdecrypt_generic($enc, $encryptedData);
        mcrypt_generic_deinit($enc);
        mcrypt_module_close($enc);
    
        // PKCS7 Padding from: https://gist.github.com/1077723
        $dataPad = ord($data[strlen($data)-1]);
    
        return substr($data, 0, -$dataPad);
    }
    

    I don't know much about mcrypt either, so I just kinda hacked these together. I md5 the key so it's always 32 characters (the max key length), and I randomly calculate an "Initialization Vector".

    Using PKCS7 Padding is better because you can have strings that end in white space (as trim would remove that), also the encryption is more efficient when the string is a certain length.

    I'm using AES 256 (MCRYPT_RIJNDAEL_256) here, but AES 192 (MCRYPT_RIJNDAEL_192) would work too.

    Demo: http://ideone.com/WA5Tk

提交回复
热议问题