Note that there are some explanatory texts on larger screens.

plurals
  1. POPHP: mcrypt mangles beginning of string to garbage
    primarykey
    data
    text
    <p>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 <em>additional</em> garbage, instead my string is <em>altered</em>.) 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. </p> <p>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.</p> <pre class="lang-php prettyprint-override"><code>$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; } </code></pre> <p>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)?</p> <p>Storing the encrypted data is not the problem; decrypting it immediately after encryption without storing it to a database results in the same errors.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload