Skip to content

Instantly share code, notes, and snippets.

@arik-so
Last active December 29, 2015 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arik-so/66c980ec490b07f81c4c to your computer and use it in GitHub Desktop.
Save arik-so/66c980ec490b07f81c4c to your computer and use it in GitHub Desktop.
PHP Diffie Hellman Implementation
<?php
namespace Tests\ArikCrypto;
use BitcoinPHP\BitcoinECDSA\BitcoinECDSA;
class ECCTest extends \PHPUnit_Framework_TestCase {
public function testDiffieHellman() {
$ecdsa1 = new BitcoinECDSA();
$ecdsa1->generateRandomPrivateKey(mcrypt_create_iv(32));
$ecdsa2 = new BitcoinECDSA();
$ecdsa2->generateRandomPrivateKey(mcrypt_create_iv(32));
$pub1 = $ecdsa1->getPubKeyPoints();
$priv1 = $ecdsa1->getPrivateKey();
$pub2 = $ecdsa2->getPubKeyPoints();
$priv2 = $ecdsa2->getPrivateKey();
$productA = $this->diffieHellman($pub1, $priv2);
$productB = $this->diffieHellman($pub2, $priv1);
var_dump($productA);
var_dump($productB);
$this->assertEquals($productA, $productB);
}
private function diffieHellman($publicKeyPoints, $privateKey){
$ecdsa = new BitcoinECDSA();
$normalizedPublicKey = [
'x' => '0x'.$publicKeyPoints['x'],
'y' => '0x'.$publicKeyPoints['y']
];
$product = $ecdsa->mulPoint($privateKey, $normalizedPublicKey);
$secretPoints = [
'x' => gmp_strval($product['x'], 16),
'y' => gmp_strval($product['y'], 16)
];
return $secretPoints;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment