Should I Trim the Decrypted String after mcrypt_decrypt?

后端 未结 4 800
一整个雨季
一整个雨季 2021-02-07 20:40

I have a code that goes something like:

$cipher_alg = MCRYPT_RIJNDAEL_128;
$decrypted_string = mcrypt_decrypt($cipher_alg, $key, 
$encrypted_string , MCRYPT_MODE         


        
4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 21:03

    In my implementation of TripleDES, I found the decrypted string was padded with \5 or \6 characters. This wasn't the expected \0 or \4 characters mentioned above or in the PHP.net examples. To determine the ASCII value of the padding character use the ord() function. ord() works on a single character so use str_split() to break up a string or access the character directly with array notation - $string[5].

    Final trim result - trim($decrypt, "\0..\32");

    Final code result -

        $key        = "encryption key";
        $encrypt    = base64_decode($encrypt);
        $iv_size    = mcrypt_get_iv_size(MCRYPT_3DES, MCRYPT_MODE_ECB);
        $iv         = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypt    = mcrypt_decrypt(MCRYPT_3DES, $key, $encrypt, MCRYPT_MODE_ECB, $iv);
        $final      = trim($decrypt, "\0..\32"); // removes potential null padding
    

提交回复
热议问题