How to encrypt data in PHP

Sep 27, 2007 14:20 GMT  ·  By

The best way to protect data transfers between client and server is the SSL/SSH protocol. Unfortunately, this protocol doesn`t protect the data stored in the database. SSL is an on-the-wire protocol. Once an attacker gains access to your database directly (bypassing the webserver), the stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.

The only solution for your data is to encrypt using an encryption package available on the web or to create your own encryption package. To create the encryption package, PHP provides you several extensions that cover a wide range of encryption functions. For example, Mcrypt allows users to encrypt files or data streams without having to be cryptographers. Mcrypt supports the following encryption algorithms: DES, TripleDES, Blowfish (default), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB cipher modes. Also it supports RC6 and IDEA, but these are considered not free. To install it you have to follow the next steps: uncomment line "extension=php_mcrypt.dll" in php.ini, download libmcrypt.dll and put it in System32 folder. Before that, don`t forget to compile PHP with the --with-mcrypt[=DIR] parameter to enable this extension.

Another great encryption package is Mhash which provides an interface to many hash algorithms. Library supports the algorithms: SHA1, SHA160, SHA192, SHA224, SHA384, SHA512, HAVAL128, HAVAL160, HAVAL192, HAVAL224, HAVAL256, RIPEMD128, RIPEMD256, RIPEMD320, MD4, MD5, TIGER, TIGER128, TIGER160, ALDER32, CRC32, CRC32b, WHIRLPOOL, GOST, SNEFRU128, SNEFRU256. To install it, you have to compile PHP with --with-mhash[=DIR] parameter. In case of truly hidden data, if its raw representation is not needed, hashing may also be taken into consideration. The most used hash function is MD5 (Message-Digest algorithm 5) and it is also used to check integrity of the files. Unfortunately, the latest security flaws that affected this function made most of the cryptographers recommend other algorithms, for example SHA-1.