I need medium to strong encryption on serverside, so I thought I would use mcrypt with PHP. If I use the functions below the beginning of my original string turns into binary garbage after decryption. (This is not the usual problem of getting appended additional garbage, instead my string is altered.) According to the documentation, mcrypt_encrypt() should have padded enough characters to match the block size of the selected algorithm but I suspect it does not work.
However, if I pad it manually to the block size of 128 bit (16 bytes) of Rijndael, it doesn't work either. The only way I can get this to work is by prepending some string long enough to (likely) cover the garbaged block and add a known prefix like "DATA#" between that string and my data. After decryption that block has been partially mangled but my prefix and all data after that has been correctly decrypted.
$GLOBALS['encryptionmarker'] = 'DATA#'; function encrypt($plain, $key) { /* // workaround because beginning of decrypted string is being mangled // so we simply prefix with some text plus marker $prefix = str_pad('', 128, '#', STR_PAD_RIGHT).$GLOBALS['encryptionmarker']; $plain = $prefix.$plain; */ $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plain, MCRYPT_MODE_CFB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), MCRYPT_DEV_URANDOM)); return $encrypted; } function decrypt($encrypted, $key) { $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_CFB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CFB), MCRYPT_DEV_URANDOM)); /* // workaround: remove garbage $pos = strpos($decrypted, $GLOBALS['encryptionmarker']); $decrypted = trim(substr($decrypted, $pos + strlen($GLOBALS['encryptionmarker']))); */ return $decrypted; }
What's wrong with my functions? Why do I have to prefix my data like that (I consider it a dirty workaround, so I would like to fix it)?
Storing the encrypted data is not the problem; decrypting it immediately after encryption without storing it to a database results in the same errors.