PHP AES Encryption

Sometime it’s needed to use 2 way encryption for storing data. I’ve been using an AES encryption class for a little over a year now, and it is an excellent way to use FIPS Compliant AES encryption in php. The script comes in a free version (ECB mode only) and a paid version for only $10.

This is a completely standalone class that does not require the mcrypt library, and has php4 and php5 support. Encryption is available in 128, 192, and 256 bit, depending on the cipher length.

Using it is easy as this:

$my_256_key = 'MpDsw*8cQM&fez*7eBoZB^W*kP652NoW';
$initialization_vector = 'WmR&z28zWn8r*9$R';
$aes = new AES($my_256_key, "CBC", $initialization_vector);
$encrypted_string = $aes->encrypt($string_to_encrypt);
$original_string = $aes->decrypt($encrypted_string);

The cipher modes that are supported are: Electronic Codebook (ECB), Cipher Block Chaining (CBC), Cipher Feedback (CFB), and Output Feedback (OFB). —Block Cipher Modes »

If you are needing to integrate real encryption into a script, I highly recommend this class. It’s strong enough for storing sensitive data like credit cards (key management is another topic), and has an extremely easy interface.

Keep in mind that encryption is only as secure as the key and the key management that is used. Unlike using hash functions (Md5, SHA1), encryption can be reversed, and will considerably slow down a php script, especially so for encrypting large amounts of data.

Database Storage:
I would recommend base 64 encoding an encrypted string and then storing in a text or blob type field. Output from AES encryption will likely be corrupted by a database’s character encoding if you do not.

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
  1. anticholinergic 16 Sep, 2009

    I would recommend not using phpaes.com’s AES implementation, but rather, phpseclib.sourceforge.net’s. It’s the fastest implementation of AES around, per this:


    (compare phpaes.phps against phpseclib-aes.phps)

  2. kurapix 5 Aug, 2010

    I don’t see the point in using this class …

    You know that you have AES with mcrypt?
    The name of AES algorithm is Rijndael by the way ;).

  3. JV- 20 Oct, 2011

    phpseclib has an awesome AES implementation, but it only supports PKCS#1 padding.

    If you have access to mcrypt, you could use the AES_Encryption class to implement AES with multiple different padding methods, including: ANSI_X.923, ISO_10126, PKCS7, BIT, ZERO


Copyright © 2024 SayNoToFlash, Jamie Estep, All Rights Reserved · Theme design by Themes Boutique