Symmetric decryption

string mdecrypt_generic ( resource td, string data)

As you have seen, it takes around ten lines of code just to encrypt data, however the end result is that you get encrypted text that is exceptionally hard to decrypt without knowledge of the key and IV. Once you have mastered encryption, decryption is fairly easy as it shares most of the same concepts. Here is the same script again, this time it encrypts then decrypts the information:

<?php
    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_generic_init($td, $key, $iv);
    $plaintext = mdecrypt_generic($td, $ciphertext);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);

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

Note that we actually call mcrypt_generic_deinit() then mcrypt_generic_init() immediately afterwards - this is important for the encryption to work properly, and you must not forget to do this.

Author's Note: it is crucial that you do not forget to deinit() after you encrypt, then call init() again when you want to decrypt - if you do not believe me, try commenting these lines out and see what happens!

The output of that script is too crazy to print here because encrypted data uses a much wider range of characters than just A-Z - try the script for yourself and see what your ciphertext looks like.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Changing encryption algorithm >>

Previous chapter: Advanced symmetric encryption

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.