Skip to content

Instantly share code, notes, and snippets.

@vzool
Last active June 2, 2018 21:17
Show Gist options
  • Save vzool/5f44f44f2a9bdf62e569d296fede7140 to your computer and use it in GitHub Desktop.
Save vzool/5f44f44f2a9bdf62e569d296fede7140 to your computer and use it in GitHub Desktop.
A test that use Php-Encryption and exchange keys by Curve25519
<?php
/*
* For testing you will need the following packages:
*
* - paragonie/random_compat
*
* - defuse/php-encryption
*
* - leigh/curve25519
*/
require 'vendor/autoload.php';
require_once('defuse-crypto.phar'); // Use this version to stop EnvironmentIsBrokenException
use Defuse\Crypto\Key;
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Encoding;
// -----------------
// Aziz Server
// -----------------
$AzizPrivateKey = Key::createNewRandomKey();
$AzizPublicKey = urlencode(base64_encode(\Curve25519\publicKey($AzizPrivateKey->getRawBytes())));
// -----------------
// Bob Server
// -----------------
$BobPrivateKey = Key::createNewRandomKey();
$BobPublicKey = urlencode(base64_encode(\Curve25519\publicKey($BobPrivateKey->getRawBytes())));
/************************/
// Exchange Public Keys
/************************/
$AzizSharedKey = Key::loadFromAsciiSafeString(Encoding::saveBytesToChecksummedAsciiSafeString(
Key::KEY_CURRENT_VERSION,
\Curve25519\sharedKey($AzizPrivateKey->getRawBytes(), base64_decode(urldecode($BobPublicKey)))
));
$BobSharedKey = Key::loadFromAsciiSafeString(Encoding::saveBytesToChecksummedAsciiSafeString(
Key::KEY_CURRENT_VERSION,
\Curve25519\sharedKey($BobPrivateKey->getRawBytes(), base64_decode(urldecode($AzizPublicKey)))
));
echo "<h3>Test hash_equals:</h3>"; /// PASSED
var_dump(\hash_equals($AzizSharedKey->getRawBytes(), $BobSharedKey->getRawbytes()));
/****************************/
// Encrypt by AzizSharedKey
/***************************/
echo "<hr/><h3>Test Encrypt by AzizSharedKey:</h3>";
$original_text = "Salam, Hello & Salam ... Fellow Human beings. We are finally together. :)";
echo "<h4>original_text: $original_text</h4>";
//
$encrypted_text = Crypto::encrypt($original_text, $AzizSharedKey);
echo "<h4>encrypted_text: $encrypted_text</h4>";
/****************************/
// Decrypt by BobSharedKey
/***************************/
echo "<hr/><h3>Test Decrypt by BobSharedKey:</h3>";
$decrypted_text = Crypto::decrypt($encrypted_text, $BobSharedKey);
echo "<h4>decrypted_text: $decrypted_text</h4>";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment