Question

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.

Was it helpful?

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)

OTHER TIPS

Consider changing mode from ECB to more secure mode like CBC. To remove padding you can use rtrim($decryptedtext, "\0"). Look at example. This is default 0 padding, as mentioned before, encryption data is padded with 0 to match size of block. You can add PKCS7 padding before encrypting you can find examples here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top