Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page