Appendix C. Cryptography

In a book about security, cryptography is an expected topic. I have chosen to neglect cryptography in the majority of the book because its purpose is narrow, and developers need to pay attention to the big picture. Relying on encryption is often a red herring. It serves its purpose well, but encrypting something doesn’t magically make an application secure.

The key types of cryptography with which a PHP developer should be familiar are as follows:

  • Symmetric cryptography

  • Asymmetric (public key) cryptography

  • Cryptographic hash functions (message digests)

  • Message authentication codes (MACs)

The majority of this appendix focuses on symmetric cryptography using the mcrypt extension. Other good resources that you should review are as follows:

Storing Passwords

You should never store cleartext passwords in a database. Instead, store the hash of the password, and use a salt for best results:

    <?php

    /* $password contains the password. */

    $salt = 'SHIFLETT';
    $password_hash = md5($salt . md5($password . $salt));

    /* Store password hash. */

    ?>

When you want to determine whether a user has provided the correct password, hash the provided password using the same technique, and compare the hashes:

 <?php $salt = 'SHIFLETT'; $password_hash ...

Get Essential PHP Security 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.