Speed up development with full-stack environments for every branch.

Learn More

PHP mcrypt - Complete encryption and decryption of data

Forked from PHP mcrypt - Class to provide 2 way encryption of data.

536 Runs 2654 Views 1102 Copies
Saved

Saved

gtsolutions 373

gtsolutions
published 4 years ago

<?php
/*
 * PHP mcrypt - Complete encryption and decryption of data
 */
$input = "This is my important data I need to encrypt";

/* Open the cipher */
$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');

/* Create the IV and determine the keysize length, use MCRYPT_RAND
 * on Windows instead */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
$ks = mcrypt_enc_get_key_size($td);

/* Create key */
$key = substr(md5('very secret key'), 0, $ks);

/* Intialize encryption */
mcrypt_generic_init($td, $key, $iv);

/* Encrypt data */
$encrypted = mcrypt_generic($td, $input);

/* Terminate encryption handler */
mcrypt_generic_deinit($td);

/* Initialize encryption module for decryption */
mcrypt_generic_init($td, $key, $iv);

/* Decrypt encrypted string */
$decrypted = mdecrypt_generic($td, $encrypted);

/* Terminate decryption handle and close module */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);

/* Show string */
echo "Encrypted string : ".trim($encrypted) . "<br />\n";
echo "Decrypted string : ".trim($decrypted) . "<br />\n";
?>
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).