Chapter 14. Encryption and Security

Introduction

In a perfect world, encryption wouldn’t be necessary. Nosy people would keep their eyes on their own data, and a credit card number floating around the Internet would attract no special attention. In so many ways, however, our world isn’t perfect, so we need encryption.

Encryption scrambles data. Some data scrambling can’t be unscrambled without unreasonable amounts of processing. This is called one-way encryption . Other encryption methods work in two directions: data is encrypted; then it’s decrypted.

PHP supplies tools to encrypt and secure your data. Some tools, such as the crypt( ) and md5( ) functions, are part of PHP’s base set of functions, and some are extensions that need to be explicitly included when PHP is compiled (e.g., mcrypt, mhash, and cURL).

The crypt( ) function does one-way DES encryption using the first eight characters of plaintext to calculate the ciphertext. You pass it the plaintext to encrypt (and a salt, which strengthens the encryption), and it returns the encrypted ciphertext. PHP generates a random salt if you don’t supply one:

print crypt('shrimp','34');
34b/4qaoXmcoY

If the constant CRYPT_MD5 is set to 1, crypt( ) can do MD5 encryption. To tell PHP to use MD5 encryption, start the salt with $1$:

print crypt('shrimp','$1$seasalt!');
$1$seasalt!$C8bRD475BC3T4EvjjmR9I.

Recipe 14.5 discusses crypt( ). It is most widely used for encrypting passwords.

mcrypt is a more full-featured encryption library ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.