Re: Padding with mcrypt_generic

From: Date: Tue, 15 Jan 2002 01:55:46 +0000
Subject: Re: Padding with mcrypt_generic
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-80512@lists.php.net to get a copy of this message
Ben Sinclair wrote:
I'm trying to use mcrypt_generic and it works fine except it pads the data with ^@'s when, according to the manual page, the length of the data is not n * blocksize. I've been trying to remove the padding from my decrypted data using something like "$string = str_replace("^@","",$string);", but it doesn't seem to work right (^@ is a single character, not just "^" . "@"). Has anyone had to do this before and found a solution? -- Ben Sinclair ben@yourwebwill.com
I worked around this by padding the plaintext myself. Basically, add NUL (character 0) bytes so that your plaintext becomes an exact multiple of blocksize. Then change the very last byte to the number of padding bytes used. If the plaintext is already an exact multiple of blocksize, then pad with an entire block. On decryption, reverse the process, and you'll have your original string back exactly the way you started. Here are two functions that I use for this: (note: I modified these slightly from the originals without testing) function pad_plaintext($data, $blocksize) {
        $buffer = "";
        $numpad = $blocksize - (strlen($data) % $blocksize);
        $nul_str = chr(0);
        $buffer = $data . str_repeat($nul_str, $numpad);
        $buffer[strlen($buffer) - 1] = chr($numpad);
        return($buffer);
} function depad_plaintext($data) {
        $buffer = "";
        $numpad = ord($data[strlen($data) - 1]);
        $buffer = substr($data, 0, -1 * $numpad);
        return($buffer);
} HTH, --Joe

« previous php.general (#80512) next »