PHP Classes

bug in hextToString

Recommend this page to a friend!

      AES Cipher  >  All threads  >  bug in hextToString  >  (Un) Subscribe thread alerts  
Subject:bug in hextToString
Summary:some strings fail to decrypt because of hexToString
Messages:4
Author:P. David Flammer
Date:2014-08-29 00:23:50
 

  1. bug in hextToString   Reply   Report abuse  
Picture of P. David Flammer P. David Flammer - 2014-08-29 00:23:50
It looks like there is a problem in the hexToString function in AES. Replace it with this, and it should be fixed (at least for all the strings I tested):

public function hexToString($hex) {
$str="";
for($i=0; $i<strlen($hex); $i=$i+2 ) {
$str .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $str;
}

  2. Re: bug in hextToString   Reply   Report abuse  
Picture of P. David Flammer P. David Flammer - 2014-08-29 00:27:12 - In reply to message 1 from P. David Flammer
or if you're using php>5.4, just use bin2hex/hex2bin.

  3. Re: bug in hextToString   Reply   Report abuse  
Picture of P. David Flammer P. David Flammer - 2014-08-29 00:30:07 - In reply to message 2 from P. David Flammer
Also, in order for decrypted strings to match, sometimes you need to trim the decrypted string; some extra "white" characters get added upon decryption. I've noticed this with other encryption libraries as well.

  4. Re: bug in hextToString   Reply   Report abuse  
Picture of P. David Flammer P. David Flammer - 2014-08-29 01:13:29 - In reply to message 3 from P. David Flammer
Last fix. If the last chunk is less than 16 bytes, you need to right pad it with zeros; otherwise you get an unpredictable shift in the hex. Replace the encrypt function with the following to get it to work in AESCipher:

public function encrypt($content, $password) {
$key = $this->_generateKey($password);
$input = str_split($this->_cipher->stringToHex($content), self::BYTE_LIMIT*2);
$output = '';
foreach ($input as $chunk)
{
if(strlen($chunk) < self::BYTE_LIMIT*2)
{
// Pad it on the right with zeros if it's short.
$chunk = str_pad($chunk,self::BYTE_LIMIT*2,'0',STR_PAD_RIGHT);
}
$output .= $this->_cipher->encrypt($chunk, $key);
}
return $this->_cipher->hexToString($output);
}