Friday, July 26, 2013

Symmetric-Key Encryption: AES in PHP and what "mode" to choose

Doing some encryption? Want to use the same key for encryption and decryption? Well, I did too. Here are the results of a lot of internet searching.

The 'mcrypt' extension in PHP is the place to go for AES, symmetric-key encryption. AES is safe and secure – the US government has even ok'd 192-bit AES (and up) for top secret documents. You can install it by running yum install php-mcrypt (if you're running Red Hat or CentOS) and then it is available for your coding pleasure.

The next decision is what "mode of operation" to use for your AES encryption. There are a few different ways to do all the fancy math and permutations. Some are more secure than others. You'll notice that when using the mcrypt_encrypt() command, you have to specify the mode as the 4th parameter. You have a choice to make. PHP 5.4 currently has the following modes available (you can find all the options available to your environment by using mcrypt_list_modes):
  • cbc
  • cfb
  • ctr
  • ecb
  • ncfb
  • nofb
  • ofb
  • stream
If you're in the same boat I'm in – aka "not a cryptographer" boat – then this is just a nice list of letters. But there are a lot of cryptographers who put a lot of good info on the interwebs, thank goodness. I ran across this article on AES usage tips, then there is the overly-neutral Wikipedia article, and a good-enough answer to a similar question on Stack Exchange.

Here are my collected thoughts on the matter:
  1. One glaring thing I came away with from all these sources is this: DON'T USE ECB
  2. The second thing I came away with is this: CTR would be the ideal, if it was available. This is because it does some authentication to make sure the encrypted message really is an encrypted message and not some sort of cryptographic trojan horse. (The simple solution to this is to make sure you HMAC hash your encrypted text to make sure it isn't tampered with.)
  3. The last thing I came away with is: Use OFB or CFB because they are pretty darn good and available in mycrpt.
Other thoughts? Do you know of even better articles on modes of encryption? I'm all ears!

Tuesday, July 2, 2013

Checking the last SQL statements used by PHPActiveRecord

I'm using PHP-ActiveRecord on a project and am loving it. But there are some things to learn and as a guy coming from the write-your-own-sql world, I do occasionally want to check what SQL queries that ActiveRecord is sending out there. I've used this bit of a code a few times to do so and it is immensely helpful for me as I try to see if I'm using this package correctly:

echo Model::table()->last_sql;

Pop that in after you do your Model::find() or Model->save() or whatever, just be sure to swap 'Model' out with your model's actual name.