Created
April 16, 2018 23:26
-
-
Save jdc-cunningham/f56b20ce24be56c5ced8da57cb91285a to your computer and use it in GitHub Desktop.
encrypt decrypt example using php-defuse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// error checking | |
ini_set('display_errors', 1); | |
// require php-defuse.phar | |
require_once('defuse-crypto.phar'); | |
use Defuse\Crypto\Crypto; | |
use Defuse\Crypto\Key; | |
use Defuse\Crypto\KeyProtectedByPassword; | |
$phrase = 'Encrypt me peasant'; | |
$key_name = 'mykey'; | |
$pass = 'sample'; // this would be based on the user's actual password when they login, you store hashed pass so it's not related to that | |
// dump unencrypted text | |
echo $phrase . '<br><br>'; | |
// check memcache | |
$server = 'localhost'; | |
if (!empty($_REQUEST['server'])) { | |
$server = $_REQUEST['server']; | |
} | |
$memcache = new Memcache; | |
$isMemcacheAvailable = @$memcache->connect($server); | |
// check if key exists | |
if ($isMemcacheAvailable) { | |
// create key, assuming user doesn't have one yet | |
$protected_key = KeyProtectedByPassword::createRandomPasswordProtectedKey($pass); | |
$protected_key_encoded = $protected_key->saveToAsciiSafeString(); | |
$user_key = $protected_key->unlockKey($pass); | |
$user_key_encoded = $user_key->saveToAsciiSafeString(); | |
$memcache->set($key_name, $user_key_encoded, 0, 86400); // set for 1 day, destroy on logout | |
} | |
else { | |
// can't encrypt | |
} | |
// get key | |
$user_key_encoded = $memcache->get($key_name);// ... get it out of the session ... | |
$user_key = Key::loadFromAsciiSafeString($user_key_encoded); | |
// encrypt the text | |
$encrypted_phrase = Crypto::encrypt($phrase, $user_key); | |
// dump encrypted text | |
echo 'encrypted: ' . $encrypted_phrase . '<br><br>'; | |
// decrypt text | |
try { | |
$decrypted_phrase = Crypto::decrypt($encrypted_phrase, $user_key); | |
echo 'decrypted: ' . $decrypted_phrase . '<br><br>'; | |
} catch (Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException $ex) { | |
echo "failed to decrypt"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment