14.7. Encrypting and Decrypting Data

Problem

You want to encrypt and decrypt data using one of a variety of popular algorithms.

Solution

Use PHP’s mcrypt extension:

$key  = 'That golden key that opes the palace of eternity.';
$data = 'The chicken escapes at dawn. Send help with Mr. Blue.';
$alg  = MCRYPT_BLOWFISH;
$mode = MCRYPT_MODE_CBC;

$iv = mcrypt_create_iv(mcrypt_get_iv_size($alg,$mode),MCRYPT_DEV_URANDOM);
$encrypted_data = mcrypt_encrypt($alg, $key, $data, $mode, $iv);
$plain_text = base64_encode($encrypted_data);

print $plain_text."\n";
$decoded = mcrypt_decrypt($alg,$key,base64_decode($plain_text),$mode,$iv);
print $decoded."\n";
NNB9WnuCYjyd3Y7vUh7XDfWFCWnQY0BsMehHNmBHbGOdJ3cM+yghABb/XyrJ+w3xz9tms74/a70=
               The chicken escapes at dawn. Send help with Mr. Blue.

Discussion

The mcrypt extension is an interface with mcrypt, a library that implements many different encryption algorithms. The data is encrypted and decrypted by mcrypt_encrypt( ) and mcrypt_decrypt( ), respectively. They each take five arguments. The first is the algorithm to use. To find which algorithms mcrypt supports on your system, call mcrypt_list_algorithms( ) . The full list of mcrypt algorithms is shown in Table 14-1. The second argument is the encryption key; the third argument is the data to encrypt or decrypt. The fourth argument is the mode for the encryption or decryption (a list of supported modes is returned by mcrypt_list_modes( ) ). The fifth argument is an initialization vector (IV), used by ...

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.