RE: [PHP-DEV] PHP 4.0 Bug #4854: trim doesn't remove the null character in a string

From: Date: Wed, 07 Jun 2000 15:12:56 +0000
Subject: RE: [PHP-DEV] PHP 4.0 Bug #4854: trim doesn't remove the null character in a string
References: 1  Groups: php.dev 
Request: Send a blank email to php-dev+get-20476@lists.php.net to get a copy of this message
> I have been storing encyrpted strings in a mysql database. When > I retrieve the string and decyrpted, it appears to add null > characters to multiples of 8. This is a function of your decryption algorhythm (mcrypt, I'm guessing), and not really a bug in MySQL/PHP, by the way. Most cryptos do things in blocks of 8 bytes, so the string you are encrypting is padded with null (or garbage) until its length%8 is zero. Then it gets encrypted. When you decrypt, all those nulls/garbage are still there. One problem with your solution (although probably not in your case, but more in the general case) is what if your plaintext string ends in \0? One solution I've used is similar to this: function encrytpt($string) { # calculate the block size $block_size = mcrypt_get_block_size(MCRYPT_BLOWFISH); # get length of string $len = strlen($string); # calculate how many chars in the string are # in the last block $rem = $len % $block_size; # padd the string with NULL until there is only # one character left in the last block while ( (strlen($string)%$block_size) != ($block_size-1) ) { $string .= "\0"; } # then add the remainder info to the end $string .= pack("C1",$rem); # do the encryption and return return mcrypt_CBC(MCRYPT_BLOWFISH, $key, $string, CRYPT_ENCRYPT); } And then ... fucntion decrypt($string) { # calculate the block size $block_size = mcrypt_get_block_size(MCRYPT_BLOWFISH); # decrypt it $return = mcrypt_CBC(MCRYPT_BLOWFISH, $key, $string, MCRYPT_DECRYPT); # read off the remainder info from the end $rem = ord(substr($return,-1)); # and strip the padding do { $return = substr($return,0,-1); } while ((strlen($return)%$block_size) != $rem); # return plaintext return $return; } __________________________________________________________________ Colin Viebrock easyDNS Technologies Co-Founder control your domain http://www.easyDNS.com

« previous php.dev (#20476) next »