I am trying to encrypt some text messages using mcrypt from php and the cipher Rijndael, but I am not sure about the MCRYPT_MODE_modename (according to PHP's manual these are available "ecb", "cbc", "cfb", "ofb", "nofb" or "stream" but I read there are actually a few more). I have no idea what each one do or how to use them.
I read two things, that ECB mode should not be used and MCRYPT_RAND neither. They didn't explain why. For the ECB mode I guess it's because it always generate the same encrypted output for the same plain text (maybe this could be used for an attack), no idea about MCRYPT_RAND (mentioned by @azz here).
My question is, what mcrypt mode should I use, and it would be great to see an example of php code using it because all the examples I found use ECB. The strings I am trying to encrypt will contain only ascii text, and variable length, not bigger than 500 chars.
ecb is the simplest and has weaknesses so it is not recommended (http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation). cbc is considered significantly stronger than ecb. Some of the others may be even stronger than cbc but they are all stream related so cbc should suit your needs.
From... http://us.php.net/manual/en/mcrypt.constants.php...
I'm not sure why MCRYPT_RAND is recommended against but it may be because the system random number generator on many systems is not considered to be truely random. There are only two alternatives and they may not be available depending on your system and PHP version. From... http://php.net/manual/en/function.mcrypt-create-iv.php...
The code below is just a quick sample. It works but I can't attest to it's strength.
The ECB mode is not secure because it doesn't introduce randomness in the encrypted data. That basically means you will see the same patterns of the input in the output (i.e. see the image reported here, it's an "encrypted" version of Tux, the logo of Linux).
The MT_RAND is not considered secure because it uses the random number generator of the operating system (the
rand()
function of PHP).For cryptography purposes it's better to use
MCRYPT_DEV_RANDOM
(read data from /dev/random) orMCRYPT_DEV_URANDOM
(read data from /dev/urandom).The most used and secure encryption modes, available with Mcrypt, are CBC and CTR mode and are fine for general use cases. It's always better to use encryption + authentication (i.e. encrypt-then-authenticate using HMAC). For instance, the CBC mode without authentication is affected by the Padding Oracle attack.