Search code examples
phpsessioncookiesnullmcrypt

From where are these null bytes appearing?


For an API test suite I am using the following code to save the user's password encrypted:

$encryptionKey = sha1(microtime(true) . mt_rand(PHP_INT_MAX / 10, PHP_INT_MAX));
setcookie('key', $encryptionKey, 0);

$_SESSION['username'] = $_POST['username'];
$_SESSION['encryptedPassword'] = mcrypt_encrypt(MCRYPT_BLOWFISH, $encryptionKey, $_POST['password'], MCRYPT_MODE_ECB);

To retrieve the password, I am using the following code:

$password = mcrypt_decrypt(MCRYPT_BLOWFISH, $_COOKIE['key'], $_SESSION['encryptedPassword'], MCRYPT_MODE_ECB);

It appears that sometimes five null bytes are appended to the value stored. Thus, var_dump($password) returns the following:

string(8) "123"

var_export($password) returns the following:

'123' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . '' . "\0" . ''

Note that we see three characters, yet var_dump() insists that there are eight. Right now I am using trim() to work around this issue, but I would like to know how to solve this issue.

Thank you.


Solution

  • Most encryption algorithms (this one included) work on fixed block sizes, typically of 8 bytes. So the value that is actually encoded in this case is 123\0\0\0\0\0 (which is actually slightly unusual, many encryption algorithms use the padding size as the padding - e.g. 123\5\5\5\5\5)