O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Encryption

Practicing the art of encryption , both for data you store locally and for data you send to and from your clients and other data consumers, is not only recommended, but it is a staple requirement for anything done in conjunction with the Internet.

Encryption is undoubtedly the most complicated topic PHP programmers have to face, partially because encryption is inherently complex, and partially because the PHP extension designed to handle encryption seems to have been designed for encryption experts to use, as opposed to normal people!

Encrypting Data

To encrypt data, you need to use seven different functions , which are: mcrypt_module_open(), mcrypt_create_iv(), mcrypt_enc_get_iv_size(), mcrypt_enc_get_key_size(), mcrypt_generic_init(), mcrypt_generic(), mcrypt_generic_deinit(), and finally, mcrypt_module_close().

The easiest way to learn these functions is just to use them, because they accept limited input and give limited output. This script is a good place to start:

    srand((double)microtime()*1000000 );
    $td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', MCRYPT_MODE_CFB, '');
    $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    $ks = mcrypt_enc_get_key_size($td);
    $key = substr(sha1('Your Secret Key Here'), 0, $ks);
    mcrypt_generic_init($td, $key, $iv);
    $ciphertext = mcrypt_generic($td, 'This is very important data');
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

    print $iv . "\n";
    print trim($ciphertext) . "\n";

The script starts with the random number ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required