I've been testing out the various modes available in PHP's mcrypt
function. ECB is the mode used in most tutorials, but isn't recommended by both the just linked page and some users, so I reckon that either CBC or CFB should do the trick.
The PHP documentation isn't too fat in it's comparision of the different modes available to mcrypt
and instead refers to the book of 'Applied Cryptography by Schneier', which I am not too keen to buy for the moment.
So which of the mcrypt
-modes do I want to use and why?
The mcrypt extension is an interface to the mcrypt cryptography library. This extension is useful for allowing PHP code using mcrypt to run on PHP 7.2+. The mcrypt extension is included in PHP 5.4 through PHP 7.1.
ext/mcrypt ¶ The mcrypt extension has been abandonware for nearly a decade now, and was also fairly complex to use. It has therefore been deprecated in favour of OpenSSL, where it will be removed from the core and into PECL in PHP 7.2.
You can install Mcrypt from the PHP Source Tree as a module if you choose. Enable the module by adding: 'extension=mcrypt.so' to PHP. ini. Done!
Determine if the mcrypt extension is loaded in any of the following ways: Set up a phpinfo. php file in the web server's root directory and examine the output in a web browser. Run the following command: $ php -r "phpinfo();" | grep mcrypt.
mcrypt
actually implements more modes than listed, you can use the string names to access them:
cbc
– CBC modecfb
– 8-bit CFB mode;ncfb
– block-size CFB mode;nofb
– OFB mode (not ofb
);ctr
– CTR mode.The modes differ in implementation details, so their suitability depends on your data and environment.
Padding:
CBC mode only encrypts complete blocks, so mcrypt
pads your plaintext with zero bytes unless you implement your own padding.
CFB, OFB and CTR modes encrypt messages of any length.
Initialization vector:
CBC and CFB modes require a random IV (don't use MCRYPT_RAND
).
OFB mode merely requires a unique IV (e.g. a global counter, maybe the database primary key if rows are never modified or deleted).
CTR requires that each counter block is unique (not just the IV of the message, which is the first counter block, but the rest, formed by incrementing the counter block by 1 for each block of the message).
More information in the NIST recommendations.
There are differences in performance which should be unimportant in PHP, such as whether encryption or decryption can be parallelized and how many cipher iterations are used per block (usually one, but 16 in 8-bit CFB mode).
There are differences in malleability which should be unimportant because you will apply a MAC.
And there may be differences in their security, but for that you should consult a cryptographer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With