Skip to content
Browse files

Initial commit of Crypt_DiffieHellman

  • Loading branch information...
1 parent 04a01fa commit f1da33b8d6de44e21922092152393819d59040bf Pádraic Brady committed Sep 15, 2007
View
417 DiffieHellman.php
@@ -0,0 +1,417 @@
+<?php
+/**
+ * Implementation of the Diffie-Hellman Key Exchange cryptographic protocol
+ * in PHP5. Enables two parties without any prior knowledge each other
+ * establish a secure shared secret key across an insecure channel
+ * of communication.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2005-2007 Pádraic Brady <padraic.brady@yahoo.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Crypt
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version $Id$
+ * @link http://
+ */
+
+/** Crypt_DiffieHellman_Math */
+require_once 'Crypt/DiffieHellman/Math.php';
+
+/**
+ * Crypt_DiffieHellman class
+ *
+ * Example usage:
+ * Bob and Alice have started to communicate and wish to establish a
+ * shared common secret key with which to sign messages.
+ * Both establish two common pieces of information:
+ * - a large prime number
+ * - a generator number
+ * Both also generate a private key (different for each) and a public
+ * key. They then transmit their public keys to each other, and agree
+ * on the prime and generator also.
+ * Both then perform identical sets of Diffie Hellman calculations and
+ * calculate a key which only each could calculate.
+ *
+ * This is secure for a very simple reason - no other party can reverse
+ * engineer the public keys to get hold of the private keys which are
+ * essential pieces of calculating the Diffie-Hellman shared secret.
+ * The algorithm ensures this by using Modular Exponentiation which
+ * expresses a one-way-function behaviour (it's computationally
+ * infeasible to reverse it).
+ *
+ * Using the data below, both will agree a shared secret key of 117.
+ *
+ * Alice: prime = 563
+ * generator = 5
+ * private key = 9
+ * Bob: prime = 563
+ * generator = 5
+ * private key = 14
+ *
+ * $alice = new Crypt_DiffieHellman(563, 5, 9);
+ * $alice_pubKey = alice->generateKeys()->getPublicKey();
+ * $bob = new Crypt_DiffieHellman(563, 5, 14);
+ * $bob_pubKey = $bob->generateKeys()->getPublicKey();
+ *
+ * // the public keys are then exchanged (with agreed prime and generator)
+ *
+ * $alice_computeKey = $alice->computeSecretKey($bob_pubKey)->getSharedSecretKey();
+ * $bob_computeKey = $bob->computeSecretKey($alice_pubKey)->getSharedSecretKey();
+ *
+ * assert($alice_computeKey == $bob_computeKey);
+ *
+ * Alice and Bob have now established the same shared secret key of 117.
+ * They may now sign exchanged messages which the other party may then
+ * authenticate upon receipt.
+ *
+ * In order to facilitate the practice of transmitting large integers in
+ * their binary form, input and output methods may accept an additional
+ * parameter of Crypt_DiffieHellman::BINARY to tell this method when the
+ * input/output should be converted from, or to, binary form. An alternate
+ * parameter of Crypt_DiffieHellman::BTWOC is used only for output methods
+ * and returns the binary big-endian twos complement of the binary form to
+ * maintain consistent binary conversion across platforms.
+ *
+ * Although the example above uses a simple prime number, it is important
+ * to always use a sufficiently large prime, preferably one of the primes
+ * deemed to have positive cryptographic qualities. The generator is
+ * always a number less than the prime number.
+ *
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @copyright 2005-2007 Pádraic Brady
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @link http://
+ * @version @package_version@
+ * @access public
+ */
+class Crypt_DiffieHellman
+{
+
+ /**
+ * Default large prime number; required by the algorithm.
+ *
+ * @var string
+ */
+ private $_prime = null;
+
+ /**
+ * The default generator number. This number must be greater than 0 but
+ * less than the prime number set.
+ * @var string
+ */
+ private $_generator = null;
+
+ /**
+ * A private number set by the local user. It's optional and will
+ * be generated if not set.
+ *
+ * @var string
+ */
+ private $_privateKey = null;
+
+ /**
+ * BigInteger support object courtesy of Zend_Math with some additional
+ * functions such as binary conversion and a RNG method which attempts to
+ * use /dev/urandom or a less cryptographically secure algorithm if a
+ * system based RNG cannot be found.
+ *
+ * @var Crypt_DiffieHellman_Math
+ */
+ private $_math = null;
+
+ /**
+ * The public key generated by this instance after calling generateKeys().
+ *
+ * @var string
+ */
+ private $_publicKey = null;
+
+ /**
+ * The shared secret key resulting from a completed Diffie Hellman
+ * exchange
+ *
+ * @var string
+ */
+ private $_secretKey = null;
+
+ /**
+ * Constants; used to define inputs or outputs as binary or big numbers.
+ * Binary form is often used as the exchange form for public keys.
+ */
+ const BINARY = 'binary';
+ const NUMBER = 'number';
+ const BTWOC = 'btwoc';
+
+ /**
+ * Constructor; if set construct the object using the parameter array to
+ * set values for Prime, Generator and Private.
+ * If a Private Key is not set, one will be generated at random.
+ *
+ * @param string|integer $prime
+ * @param string|integer $generator
+ * @param string|integer $privateKey
+ * @param string $privateKeyType
+ * @param string $mathExtension
+ */
+ public function __construct($prime, $generator, $privateKey = null, $privateKeyType = null, $mathExtension = null)
+ {
+ $this->setPrime($prime);
+ $this->setGenerator($generator);
+ if (!is_null($privateKey)) {
+ if (is_null($privateKeyType)) {
+ $privateKeyType = self::NUMBER;
+ }
+ $this->setPrivateKey($privateKey, $privateKeyType);
+ }
+ $this->setBigIntegerMath($mathExtension);
+ }
+
+ /**
+ * Generate own public key. If a private number has not already been
+ * set, one will be generated at this stage.
+ *
+ * @return Crypt_DiffieHellman
+ */
+ public function generateKeys()
+ {
+ $this->_publicKey = $this->_math->powmod($this->getGenerator(), $this->getPrivateKey(), $this->getPrime());
+ return $this;
+ }
+
+ /**
+ * Returns own public key for communication to the second party to this
+ * transaction.
+ *
+ * @param string $type
+ * @return string
+ */
+ public function getPublicKey($type = self::NUMBER)
+ {
+ if (is_null($this->_publicKey)) {
+ require_once 'Crypt/DiffieHellman/Exception.php';
+ throw new Crypt_DiffieHellman_Exception('A public key has not yet been generated using a prior call to generateKeys()');
+ }
+ if ($type == self::BINARY) {
+ return $this->_math->toBinary($this->_publicKey);
+ } elseif ($type == self::BTWOC) {
+ return $this->_math->btwoc($this->_math->toBinary($this->_publicKey));
+ }
+ return $this->_publicKey;
+ }
+
+ /**
+ * Compute the shared secret key based on the public key received from the
+ * the second party to this transaction. This should agree to the secret
+ * key the second party computes on our own public key.
+ * Once in agreement, the key is known to only to both parties.
+ * By default, the function expects the public key to be in binary form
+ * which is the typical format when being transmitted.
+ *
+ * @param string $publicKey
+ * @param string $type
+ * @return void
+ */
+ public function computeSecretKey($publicKey, $type = self::NUMBER)
+ {
+ if ($type == self::BINARY) {
+ $publicKey = $this->_math->fromBinary($publicKey);
+ }
+ if (!preg_match("/^\d+$/", $publicKey)) {
+ require_once('Crypt/DiffieHellman/Exception.php');
+ throw new Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number');
+ }
+ $this->_secretKey = $this->_math->powmod($publicKey, $this->getPrivateKey(), $this->getPrime());
+ return $this;
+ }
+
+ /**
+ * Return the computed shared secret key from the DiffieHellman transaction
+ *
+ * @param string $type
+ * @return string
+ */
+ public function getSharedSecretKey($type = self::NUMBER)
+ {
+ if (!isset($this->_secretKey)) {
+ require_once('Crypt/DiffieHellman/Exception.php');
+ throw new Crypt_DiffieHellman_Exception('A secret key has not yet been computed; call computeSecretKey()');
+ }
+ if ($type == self::BINARY) {
+ return $this->_math->toBinary($this->_secretKey);
+ } elseif ($type == self::BTWOC) {
+ return $this->_math->btwoc($this->_math->toBinary($this->_secretKey));
+ }
+ return $this->_secretKey;
+ }
+
+ /**
+ * Setter for the value of the prime number
+ *
+ * @param string $number
+ * @return Crypt_DiffieHellman
+ */
+ public function setPrime($number)
+ {
+ if (!preg_match("/^\d+$/", $number) || $number < 11) {
+ require_once('Crypt/DiffieHellman/Exception.php');
+ throw new Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number or too small: should be a large natural number prime');
+ }
+ $this->_prime = (string) $number;
+ return $this;
+ }
+
+ /**
+ * Getter for the value of the prime number
+ *
+ * @param string $type
+ * @return string
+ */
+ public function getPrime($type = self::NUMBER)
+ {
+ if (!isset($this->_prime)) {
+ require_once('Crypt/DiffieHellman/Exception.php');
+ throw new Crypt_DiffieHellman_Exception('No prime number has been set');
+ }
+ if ($type == self::NUMBER) {
+ return $this->_prime;
+ }
+ return $this->_math->toBinary($this->_prime);
+ }
+
+ /**
+ * Setter for the value of the generator number
+ *
+ * @param string $number
+ * @return Crypt_DiffieHellman
+ */
+ public function setGenerator($number)
+ {
+ if (!preg_match("/^\d+$/", $number) || $number < 2) {
+ require_once('Crypt/DiffieHellman/Exception.php');
+ throw new Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number greater than 1');
+ }
+ $this->_generator = (string) $number;
+ return $this;
+ }
+
+ /**
+ * Getter for the value of the generator number
+ *
+ * @param string $type
+ * @return string
+ */
+ public function getGenerator($type = self::NUMBER)
+ {
+ if (!isset($this->_generator)) {
+ require_once('Crypt/DiffieHellman/Exception.php');
+ throw new Crypt_DiffieHellman_Exception('No generator number has been set');
+ }
+ if ($type == self::NUMBER) {
+ return $this->_generator;
+ }
+ return $this->_math->toBinary($this->_generator);
+ }
+
+ /**
+ * Setter for the value of the private number
+ *
+ * @param string|integer $number
+ * @param string $type
+ * @return Crypt_DiffieHellman
+ */
+ public function setPrivateKey($number, $type = self::NUMBER)
+ {
+ if ($type == self::BINARY) {
+ $number = $this->_math->fromBinary($number);
+ }
+ if (!preg_match("/^\d+$/", $number)) {
+ require_once('Crypt/DiffieHellman/Exception.php');
+ throw new Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number');
+ }
+ $this->_privateKey = (string) $number;
+ return $this;
+ }
+
+ /**
+ * Getter for the value of the private number
+ *
+ * @param string $type
+ * @return string
+ */
+ public function getPrivateKey($type = self::NUMBER)
+ {
+ if (!isset($this->_privateKey)) {
+ $this->setPrivateKey($this->_generatePrivateKey());
+ }
+ if ($type == self::BINARY) {
+ return $this->_math->toBinary($this->_privateKey);
+ } elseif ($type == self::BTWOC) {
+ return $this->_math->btwoc($this->_math->toBinary($this->_privateKey));
+ }
+ return $this->_privateKey;
+ }
+
+ /**
+ * Setter to pass an extension parameter which is used to create
+ * a specific BigInteger instance for a specific extension type.
+ * Allows manual setting of the class in case of an extension
+ * problem or bug.
+ *
+ * Due to the temporary nature of BigInteger wrapper, this decision
+ * is deferred to Crypt_DiffieHellman_Math which extends (in a
+ * slightly reversed way) Crypt_DiffieHellman_Math_BigInteger.
+ *
+ * @param string $extension
+ * @return void
+ */
+ public function setBigIntegerMath($extension = null)
+ {
+ $this->_math = new Crypt_DiffieHellman_Math($extension);
+ }
+
+ /**
+ * In the event a private number/key has not been set by the user,
+ * generate one at random.
+ *
+ * @return string
+ */
+ protected function _generatePrivateKey()
+ {
+ $rand = $this->_math->rand($this->getGenerator(), $this->getPrime());
+ return $rand;
+ }
+
+}
View
62 DiffieHellman/Exception.php
@@ -0,0 +1,62 @@
+<?php
+/**
+ * Exception subclass of PEAR_Exception for Crypt_DiffieHellman.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2005-2007, Pádraic Brady <padraic.brady@yahoo.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version $Id$
+ * @link http://
+ */
+
+/**
+ * PEAR_Exception
+ */
+require_once 'PEAR/Exception.php';
+
+/**
+ * Crypt_DiffieHellman_Exception
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @copyright 2005-2007 Pádraic Brady
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @link http://
+ * @version @package_version@
+ * @access public
+ */
+class Crypt_DiffieHellman_Exception extends PEAR_Exception
+{}
View
159 DiffieHellman/Math.php
@@ -0,0 +1,159 @@
+<?php
+/**
+ * Math extension wrapper for DiffieHellman with some additional helper
+ * methods for RNG and binary conversion.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2005-2007, Pádraic Brady <padraic.brady@yahoo.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version $Id$
+ * @link http://
+ */
+
+/** Crypt_DiffieHellman_Math_BigInteger */
+require_once 'Crypt/DiffieHellman/Math/BigInteger.php';
+
+/**
+ * Crypt_DiffieHellman_Math class
+ *
+ * Example usage:
+ * $math = new Crypt_DiffieHellman_Math;
+ * $binaryForm = $math->toBinary('384834813984910010746469093412498181642341794');
+ * $numberForm = $math->fromBinary($binaryForm);
+ *
+ * $math = new Crypt_DiffieHellman_Math('gmp');
+ * $randomNumber = $math->rand(2, '384834813984910010746469093412498181642341794');
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @copyright 2005-2007 Pádraic Brady
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @link http://
+ * @version @package_version@
+ * @access public
+ */
+class Crypt_DiffieHellman_Math extends Crypt_DiffieHellman_Math_BigInteger
+{
+
+ /**
+ * Generate a pseudorandom number within the given range.
+ * Will attempt to read from a systems RNG if it exists.
+ *
+ * @param string|int $min
+ * @param string|int $max
+ * @return string
+ * @todo Even more pseudorandomness would be nice...
+ */
+ public function rand($minimum, $maximum)
+ {
+ if (file_exists('/dev/urandom')) {
+ $frandom = fopen('/dev/urandom', 'r');
+ if ($frandom !== false) {
+ return fread($frandom, strlen($maximum) - 1);
+ }
+ }
+ if (strlen($maximum) < 4) {
+ return mt_rand($minimum, $maximum - 1);
+ }
+ $rand = '';
+ $i2 = strlen($maximum) - 1;
+ for ($i = 1;$i < $i2;$i++) {
+ $rand .= mt_rand(0,9);
+ }
+ $rand .= mt_rand(0,9);
+ return $rand;
+ }
+
+ /**
+ * Perform a btwoc operation on the given BigInteger number in
+ * binary form which returns the big-endian two's complement.
+ *
+ * @param string $long
+ * @return string
+ */
+ public function btwoc($long) {
+ if (ord($long[0]) > 127) {
+ return "\x00" . $long;
+ }
+ return $long;
+ }
+
+ /**
+ * Convert a Binary value into a BigInteger number
+ *
+ * @param string $binary
+ * @return string
+ */
+ public function fromBinary($binary) {
+ if (!$this instanceof Crypt_DiffieHellman_Math_BigInteger_Gmp) {
+ $big = 0;
+ $length = strlen($binary);
+ for ($i = 0; $i < $length; $i++) {
+ $big = $this->_math->multiply($big, 256);
+ $big = $this->_math->add($big, ord($binary[$i]));
+ }
+ return $big;
+ } else {
+ return $this->_math->init(bin2hex($binary), 16); // gmp shortcut
+ }
+ }
+
+ /**
+ * Convert a BigInteger number into binary
+ *
+ * @param string $big
+ * @return string
+ */
+ public function toBinary($big)
+ {
+ if (!$this instanceof Crypt_DiffieHellman_Math_BigInteger_Gmp) {
+ $compare = $this->_math->compare($big, 0);
+ if ($compare == 0) {
+ return (chr(0));
+ } else if ($compare < 0) {
+ return false;
+ }
+ $binary = null;
+ while ($this->_math->compare($big, 0) > 0) {
+ $binary = chr($this->_math->modulus($big, 256)) . $binary;
+ $big = $this->_math->divide($big, 256);
+ }
+ return $binary;
+ } else {
+ return pack("H*", gmp_strval($big, 16));
+ }
+ }
+}
View
109 DiffieHellman/Math/BigInteger.php
@@ -0,0 +1,109 @@
+<?php
+/**
+ * Math extension wrapper for DiffieHellman with some additional helper
+ * methods for RNG and binary conversion.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2005-2007, Pádraic Brady <padraic.brady@yahoo.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version $Id$
+ * @link http://
+ */
+
+/** Crypt_DiffieHellman_Math_BigInteger_Interface */
+require_once 'Crypt/DiffieHellman/Math/BigInteger/Interface.php';
+
+/**
+ * Crypt_DiffieHellman_Math_BigInteger class
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @copyright 2005-2007 Pádraic Brady
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @link http://
+ * @version @package_version@
+ * @access public
+ */
+class Crypt_DiffieHellman_Math_BigInteger
+{
+
+ /**
+ * Holds an instance of one of the three arbitrary precision wrappers.
+ *
+ * @var Crypt_DiffieHellman_Math_BigInteger_Interface
+ */
+ protected $_math = null;
+
+ /**
+ * Constructor; a Factory which detects a suitable PHP extension for
+ * arbitrary precision math and instantiates the suitable wrapper
+ * object.
+ *
+ * @todo add big_int support
+ * @throws Crypt_DiffieHellman_Math_BigInteger_Exception
+ * @return void
+ */
+ public function __construct($extension = null)
+ {
+ if ($extension == 'gmp' || (extension_loaded('gmp') || @dl('gmp.' . PHP_SHLIB_SUFFIX) || @dl('php_gmp.' . PHP_SHLIB_SUFFIX))) {
+ require_once 'Crypt/DiffieHellman/Math/BigInteger/Gmp.php';
+ $this->_math = new Crypt_DiffieHellman_Math_BigInteger_Gmp();
+ } elseif ($extension == 'bcmath' || (extension_loaded('bcmath') || @dl('bcmath.' . PHP_SHLIB_SUFFIX) || @dl('php_bcmath.' . PHP_SHLIB_SUFFIX))) {
+ require_once 'Crypt/DiffieHellman/Math/BigInteger/Bcmath.php';
+ $this->_math = new Crypt_DiffieHellman_Math_BigInteger_Bcmath();
+ } else {
+ require_once 'Crypt/DiffieHellman/Math/BigInteger/Exception.php';
+ throw new Crypt_DiffieHellman_Math_BigInteger_Exception('no big integer precision math support detected');
+ }
+ }
+
+ /**
+ * Redirect all public method calls to the wrapped extension object.
+ *
+ * @param string $methodName
+ * @param array $args
+ * @throws Zend_Math_BigInteger_Exception
+ */
+ public function __call($methodName, $args)
+ {
+ if (!method_exists($this->_math, $methodName)) {
+ require_once 'Crypt/DiffieHellman/Math/BigInteger/Exception.php';
+ throw new Crypt_DiffieHellman_Math_BigInteger_Exception('invalid method call: ' . get_class($this->_math) . '::' . $methodName . '() does not exist');
+ }
+ return call_user_func_array(array($this->_math, $methodName), $args);
+ }
+
+}
View
171 DiffieHellman/Math/BigInteger/Bcmath.php
@@ -0,0 +1,171 @@
+<?php
+/**
+ * Math extension wrapper for DiffieHellman with some additional helper
+ * methods for RNG and binary conversion.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2005-2007, Pádraic Brady <padraic.brady@yahoo.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version $Id$
+ * @link http://
+ */
+
+/** Crypt_DiffieHellman_Math_BigInteger_Interface */
+require_once 'Crypt/DiffieHellman/Math/BigInteger/Interface.php';
+
+/**
+ * Support for arbitrary precision mathematics in PHP.
+ *
+ * Crypt_DiffieHellman_Math_BigInteger_Bcmath is a wrapper across the PHP BCMath extension.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman_Math
+ * @subpackage BigInteger
+ * @author Pádraic Brady (http://blog.astrumfutura.com)
+ * @license http://framework.zend.com/license/new-bsd New BSD License
+ */
+class Crypt_DiffieHellman_Math_BigInteger_Bcmath implements Crypt_DiffieHellman_Math_BigInteger_Interface
+{
+
+ /**
+ * Initialise a big integer into an extension specific type. This is not
+ * applicable to BCMath.
+ * @param string $operand
+ * @param int $base
+ * @return string
+ */
+ public function init($operand, $base = 10)
+ {
+ return $operand;
+ }
+
+ /**
+ * Adds two arbitrary precision numbers
+ *
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function add($left_operand, $right_operand)
+ {
+ return bcadd($left_operand, $right_operand);
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function subtract($left_operand, $right_operand)
+ {
+ return bcsub($left_operand, $right_operand);
+ }
+
+ /**
+ * Compare two big integers and returns result as an integer where 0 means
+ * both are identical, 1 that left_operand is larger, or -1 that
+ * right_operand is larger.
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return int
+ */
+ public function compare($left_operand, $right_operand)
+ {
+ return bccomp($left_operand, $right_operand);
+ }
+
+ /**
+ * Divide two big integers and return result or NULL if the denominator
+ * is zero.
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string|null
+ */
+ public function divide($left_operand, $right_operand)
+ {
+ return bcdiv($left_operand, $right_operand);
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function modulus($left_operand, $modulus)
+ {
+ return bcmod($left_operand, $modulus);
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function multiply($left_operand, $right_operand)
+ {
+ return bcmul($left_operand, $right_operand);
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function pow($left_operand, $right_operand)
+ {
+ return bcpow($left_operand, $right_operand);
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function powmod($left_operand, $right_operand, $modulus)
+ {
+ return bcpowmod($left_operand, $right_operand, $modulus);
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function sqrt($operand)
+ {
+ return bcsqrt($operand);
+ }
+
+}
View
62 DiffieHellman/Math/BigInteger/Exception.php
@@ -0,0 +1,62 @@
+<?php
+/**
+ * Exception subclass of PEAR_Exception for Crypt_DiffieHellman.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2005-2007, Pádraic Brady <padraic.brady@yahoo.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version $Id$
+ * @link http://
+ */
+
+/**
+ * Crypt_DiffieHellman_Math_Exception
+ */
+require_once 'Crypt/DiffieHellman/Math/Exception.php';
+
+/**
+ * Crypt_DiffieHellman_Math_BigInteger_Exception
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @copyright 2005-2007 Pádraic Brady
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @link http://
+ * @version @package_version@
+ * @access public
+ */
+class Crypt_DiffieHellman_Math_BigInteger_Exception extends Crypt_DiffieHellman_Math_Exception
+{}
View
171 DiffieHellman/Math/BigInteger/Gmp.php
@@ -0,0 +1,171 @@
+<?php
+/**
+ * Math extension wrapper for DiffieHellman with some additional helper
+ * methods for RNG and binary conversion.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2005-2007, Pádraic Brady <padraic.brady@yahoo.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version $Id$
+ * @link http://
+ */
+
+/** Crypt_DiffieHellman_Math_BigInteger_Interface */
+require_once 'Crypt/DiffieHellman/Math/BigInteger/Interface.php';
+
+/**
+ * Support for arbitrary precision mathematics in PHP.
+ *
+ * Crypt_DiffieHellman_Math_BigInteger_Gmp is a wrapper across the PHP GMP extension.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman_Math
+ * @subpackage BigInteger
+ * @author Pádraic Brady (http://blog.astrumfutura.com)
+ * @license http://framework.zend.com/license/new-bsd New BSD License
+ */
+class Crypt_DiffieHellman_Math_BigInteger_Gmp implements Crypt_DiffieHellman_Math_BigInteger_Interface
+{
+
+ /**
+ * Initialise a big integer into an extension specific type. This is not
+ * applicable to BCMath.
+ * @param string $operand
+ * @param int $base
+ * @return string
+ */
+ public function init($operand, $base = 10)
+ {
+ return gmp_init($operand, $base);
+ }
+
+ /**
+ * Adds two arbitrary precision numbers
+ *
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function add($left_operand, $right_operand)
+ {
+ return gmp_strval(gmp_add($left_operand, $right_operand));
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function subtract($left_operand, $right_operand)
+ {
+ return gmp_strval(gmp_sub($left_operand, $right_operand));
+ }
+
+ /**
+ * Compare two big integers and returns result as an integer where 0 means
+ * both are identical, 1 that left_operand is larger, or -1 that
+ * right_operand is larger.
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return int
+ */
+ public function compare($left_operand, $right_operand)
+ {
+ return gmp_strval(gmp_cmp($left_operand, $right_operand));
+ }
+
+ /**
+ * Divide two big integers and return result or NULL if the denominator
+ * is zero.
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string|null
+ */
+ public function divide($left_operand, $right_operand)
+ {
+ return gmp_strval(gmp_div_q($left_operand, $right_operand));
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function modulus($left_operand, $modulus)
+ {
+ return gmp_strval(gmp_mod($left_operand, $modulus));
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function multiply($left_operand, $right_operand)
+ {
+ return gmp_strval(gmp_mul($left_operand, $right_operand));
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function pow($left_operand, $right_operand)
+ {
+ return gmp_strval(gmp_pow($left_operand, $right_operand));
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function powmod($left_operand, $right_operand, $modulus)
+ {
+ return gmp_strval(gmp_powm($left_operand, $right_operand, $modulus));
+ }
+
+ /**
+ * @param string $left_operand
+ * @param string $right_operand
+ * @return string
+ */
+ public function sqrt($operand)
+ {
+ return gmp_strval(gmp_sqrt($operand));
+ }
+
+}
View
52 DiffieHellman/Math/BigInteger/Interface.php
@@ -0,0 +1,52 @@
+<?php
+/**
+ * Zend Framework
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://framework.zend.com/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to license@zend.com so we can send you a copy immediately.
+ *
+ * This class forms part of a proposal for the Zend Framework. The attached
+ * copyright will be transferred to Zend Technologies USA Inc. upon future
+ * acceptance of that proposal:
+ * http://framework.zend.com/wiki/pages/viewpage.action?pageId=20369
+ *
+ * @category Zend
+ * @package Crypt_DiffieHellman_Math
+ * @subpackage BigInteger
+ * @copyright Copyright (c) 2007 Pádraic Brady (http://blog.astrumfutura.com)
+ * @license http://framework.zend.com/license/new-bsd New BSD License
+ */
+
+/**
+ * Support for arbitrary precision mathematics in PHP.
+ *
+ * Crypt_DiffieHellman_Math_BigInteger_Bcmath is a wrapper across the PHP BCMath extension.
+ *
+ * @category Zend
+ * @package Crypt_DiffieHellman
+ * @subpackage BigInteger
+ * @author Pádraic Brady (http://blog.astrumfutura.com)
+ * @license http://framework.zend.com/license/new-bsd New BSD License
+ */
+interface Crypt_DiffieHellman_Math_BigInteger_Interface
+{
+
+ public function init($operand, $base = 10);
+ public function add($left_operand, $right_operand);
+ public function subtract($left_operand, $right_operand);
+ public function compare($left_operand, $right_operand);
+ public function divide($left_operand, $right_operand);
+ public function modulus($left_operand, $modulus);
+ public function multiply($left_operand, $right_operand);
+ public function pow($left_operand, $right_operand);
+ public function powmod($left_operand, $right_operand, $modulus);
+ public function sqrt($operand);
+
+}
View
62 DiffieHellman/Math/Exception.php
@@ -0,0 +1,62 @@
+<?php
+/**
+ * Exception subclass of PEAR_Exception for Crypt_DiffieHellman.
+ *
+ * PHP version 5
+ *
+ * LICENSE:
+ *
+ * Copyright (c) 2005-2007, Pádraic Brady <padraic.brady@yahoo.com>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * The name of the author may not be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @version $Id$
+ * @link http://
+ */
+
+/**
+ * Crypt_DiffieHellman_Exception
+ */
+require_once 'Crypt/DiffieHellman/Exception.php';
+
+/**
+ * Crypt_DiffieHellman_Exception
+ *
+ * @category Encryption
+ * @package Crypt_DiffieHellman
+ * @author Pádraic Brady <padraic.brady@yahoo.com>
+ * @copyright 2005-2007 Pádraic Brady
+ * @license http://opensource.org/licenses/bsd-license.php New BSD License
+ * @link http://
+ * @version @package_version@
+ * @access public
+ */
+class Crypt_DiffieHellman_Math_Exception extends Crypt_DiffieHellman_Exception
+{}
View
43 generate_package_xml.php
@@ -0,0 +1,43 @@
+<?php
+require_once('PEAR/PackageFileManager2.php');
+PEAR::setErrorHandling(PEAR_ERROR_DIE);
+//require_once 'PEAR/Config.php';
+//PEAR_Config::singleton('/path/to/unusualpearconfig.ini');
+// use the above lines if the channel information is not validating
+$packagexml = new PEAR_PackageFileManager2;
+// for an existing package.xml use
+// $packagexml = {@link importOptions()} instead
+$e = $packagexml->setOptions(
+ array('baseinstalldir' => 'Crypt',
+ 'packagedirectory' => 'D:/xampp/htdocs/projects/pear/trunk/Crypt_DiffieHellman',
+ 'filelistgenerator' => 'file',
+ 'dir_roles' => array('docs' => 'doc', 'tests' => 'test'),
+ 'ignore' => array('generate_package_xml.php', '.svn', '.cvs')
+ )
+);
+$packagexml->setPackage('Crypt_DiffieHellman');
+$packagexml->setSummary('Implementation of Diffie-Hellman Key Exchange cryptographic protocol for PHP5');
+$packagexml->setDescription("Implementation of the Diffie-Hellman Key Exchange cryptographic protocol\nin PHP5. Enables two parties without any prior knowledge of each other\nestablish a secure shared secret key across an insecure channel\nof communication.");
+$packagexml->setChannel('pear.php.net');
+$packagexml->setAPIVersion('0.1.0');
+$packagexml->setReleaseVersion('0.1.0a3');
+$packagexml->setReleaseStability('alpha');
+$packagexml->setAPIStability('alpha');
+$packagexml->setNotes("* Updated tests location inside directory hierarchy for easier running\n* Fixed a PHP variable undefined notice\n* Full support for three input/output modes: Number (big integer string, Binary and Btwoc (big-endian two's complement)\n* Allowed for a specific BigInteger extension to be selected for use from the Crypt_DiffieHellman contructor\n* Minor typo fixes against PEAR Coding Standard\n* ");
+$packagexml->setPackageType('php');
+$packagexml->setPhpDep('5.0.0');
+$packagexml->setPearinstallerDep('1.4.0');
+$packagexml->addMaintainer('lead', 'padraic', 'Pádraic Brady', 'padraic@php.net');
+$packagexml->setLicense('New BSD License', 'http://opensource.org/licenses/bsd-license.php');
+$packagexml->generateContents();
+
+//$pkg = &$packagexml->exportCompatiblePackageFile1(); // get a PEAR_PackageFile object
+
+if (isset($_GET['make']) || (isset($_SERVER['argv']) && @$_SERVER['argv'][1] == 'make')) {
+ //$pkg->writePackageFile();
+ $packagexml->writePackageFile();
+} else {
+ //$pkg->debugPackageFile();
+ $packagexml->debugPackageFile();
+}
+?>
View
113 package.xml
@@ -0,0 +1,113 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<package packagerversion="1.4.5" version="2.0" xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
+ http://pear.php.net/dtd/tasks-1.0.xsd
+ http://pear.php.net/dtd/package-2.0
+ http://pear.php.net/dtd/package-2.0.xsd">
+ <name>Crypt_DiffieHellman</name>
+ <channel>pear.php.net</channel>
+ <summary>Implementation of Diffie-Hellman Key Exchange cryptographic protocol for PHP5</summary>
+ <description>Implementation of the Diffie-Hellman Key Exchange cryptographic protocol
+in PHP5. Enables two parties without any prior knowledge of each other
+establish a secure shared secret key across an insecure channel
+of communication.</description>
+ <lead>
+ <name>Pádraic Brady</name>
+ <user>padraic</user>
+ <email>padraic@php.net</email>
+ <active>yes</active>
+ </lead>
+ <date>2007-07-03</date>
+ <time>17:35:41</time>
+ <version>
+ <release>0.1.0a3</release>
+ <api>0.1.0</api>
+ </version>
+ <stability>
+ <release>alpha</release>
+ <api>alpha</api>
+ </stability>
+ <license uri="http://opensource.org/licenses/bsd-license.php">New BSD License</license>
+ <notes>* Updated tests location inside directory hierarchy for easier running
+* Fixed a PHP variable undefined notice
+* Full support for three input/output modes: Number (big integer string, Binary and Btwoc (big-endian two&apos;s complement)
+* Allowed for a specific BigInteger extension to be selected for use from the Crypt_DiffieHellman contructor
+* Minor typo fixes against PEAR Coding Standard
+* </notes>
+ <contents>
+ <dir baseinstalldir="Crypt" name="/">
+ <file baseinstalldir="Crypt" md5sum="287afa84fdabf27aa41ae373275ccd70" name="DiffieHellman/Exception.php" role="php" />
+ <file baseinstalldir="Crypt" md5sum="855be057326f2a95700e3cc302c7cbe3" name="DiffieHellman/Math.php" role="php" />
+ <file baseinstalldir="Crypt" md5sum="11eb59e5f41d43cbed34b90f253df124" name="DiffieHellman/Math/BigInteger.php" role="php" />
+ <file baseinstalldir="Crypt" md5sum="d29869653ff4f9968ad27bebd97b7419" name="DiffieHellman/Math/Exception.php" role="php" />
+ <file baseinstalldir="Crypt" md5sum="33fab4435fdd3633149ba213cd33862a" name="DiffieHellman/Math/BigInteger/Bcmath.php" role="php" />
+ <file baseinstalldir="Crypt" md5sum="78050a452009848a4a4bf9bb90ca82c2" name="DiffieHellman/Math/BigInteger/Exception.php" role="php" />
+ <file baseinstalldir="Crypt" md5sum="05f6f55666ee35c59c2ca6c7014aaf62" name="DiffieHellman/Math/BigInteger/Gmp.php" role="php" />
+ <file baseinstalldir="Crypt" md5sum="98a62bcbd00f31a25028793c0edaecdc" name="DiffieHellman/Math/BigInteger/Interface.php" role="php" />
+ <file baseinstalldir="Crypt" md5sum="ada66fc5037bed849043fa589cef4c41" name="tests/AllTests.php" role="test" />
+ <file baseinstalldir="Crypt" md5sum="9c41ff93af3045e5c169d70794cc4938" name="tests/DiffieHellmanTest.php" role="test" />
+ <file baseinstalldir="Crypt" md5sum="81db1d6b1750815fb7ce64512fc48ef6" name="tests/TestConfiguration.php.dist" role="test" />
+ <file baseinstalldir="Crypt" md5sum="2905836b0402bd79dbc8a54202aa133f" name="tests/TestHelper.php" role="test" />
+ <file baseinstalldir="Crypt" md5sum="72b7d83bb8992199c9ed901c4041b73f" name="DiffieHellman.php" role="php" />
+ </dir>
+ </contents>
+ <dependencies>
+ <required>
+ <php>
+ <min>5.0.0</min>
+ </php>
+ <pearinstaller>
+ <min>1.4.0</min>
+ </pearinstaller>
+ </required>
+ </dependencies>
+ <phprelease />
+ <changelog>
+ <release>
+ <version>
+ <release>0.1.0a1</release>
+ <api>0.1.0</api>
+ </version>
+ <stability>
+ <release>alpha</release>
+ <api>alpha</api>
+ </stability>
+ <date>2007-06-22</date>
+ <license>New BSD License</license>
+ <notes>* This is the proposal version...</notes>
+ </release>
+ <release>
+ <version>
+ <release>0.1.0a2</release>
+ <api>0.1.0</api>
+ </version>
+ <stability>
+ <release>alpha</release>
+ <api>alpha</api>
+ </stability>
+ <date>2007-06-29</date>
+ <license>New BSD License</license>
+ <notes>* Full support for three input/output modes: Number (big integer string, Binary and Btwoc (big-endian two&apos;s complement)
+* Allowed for a specific BigInteger extension to be selected for use from the Crypt_DiffieHellman contructor
+* Minor typo fixes against PEAR Coding Standard
+*</notes>
+ </release>
+ <release>
+ <version>
+ <release>0.1.0a3</release>
+ <api>0.1.0</api>
+ </version>
+ <stability>
+ <release>alpha</release>
+ <api>alpha</api>
+ </stability>
+ <date>2007-07-03</date>
+ <license>New BSD License</license>
+ <notes>* Updated tests location inside directory hierarchy for easier running
+* Fixed a PHP variable undefined notice
+* Full support for three input/output modes: Number (big integer string, Binary and Btwoc (big-endian two&apos;s complement)
+* Allowed for a specific BigInteger extension to be selected for use from the Crypt_DiffieHellman contructor
+* Minor typo fixes against PEAR Coding Standard
+* </notes>
+ </release>
+ </changelog>
+</package>
View
37 tests/AllTests.php
@@ -0,0 +1,37 @@
+<?php
+
+if (!defined('PHPUnit_MAIN_METHOD')) {
+ define('PHPUnit_MAIN_METHOD', 'AllTests::main');
+}
+
+require_once 'PHPUnit/Framework/TestSuite.php';
+require_once 'PHPUnit/TextUI/TestRunner.php';
+
+require_once 'TestHelper.php';
+require_once 'DiffieHellmanTest.php';
+
+class AllTests
+{
+ public static function main()
+ {
+ $parameters = array();
+
+ if (TESTS_GENERATE_REPORT && extension_loaded('xdebug')) {
+ $parameters['reportDirectory'] = TESTS_GENERATE_REPORT_TARGET;
+ }
+ PHPUnit_TextUI_TestRunner::run(self::suite(), $parameters);
+ }
+
+ public static function suite()
+ {
+ $suite = new PHPUnit_Framework_TestSuite('PEAR - Crypt_DiffieHellman');
+
+ $suite->addTestSuite('Crypt_DiffieHellmanTest');
+
+ return $suite;
+ }
+}
+
+if (PHPUnit_MAIN_METHOD == 'AllTests::main') {
+ AllTests::main();
+}
View
72 tests/DiffieHellmanTest.php
@@ -0,0 +1,72 @@
+<?php
+
+require_once 'Crypt/DiffieHellman.php';
+require_once 'PHPUnit/Framework/TestCase.php';
+
+/**
+ * Note: If this test utilises BCMath it will take anything up 2 or 3 minutes to complete. GMP
+ * is far faster if enabled for your platform.
+ */
+
+class Crypt_DiffieHellmanTest extends PHPUnit_Framework_TestCase
+{
+
+ public function testDiffieWithSpec()
+ {
+ $aliceOptions = array(
+ 'prime'=>'563',
+ 'generator'=>'5',
+ 'private'=>'9'
+ );
+ $bobOptions = array(
+ 'prime'=>'563',
+ 'generator'=>'5',
+ 'private'=>'14'
+ );
+ $alice = new Crypt_DiffieHellman($aliceOptions['prime'], $aliceOptions['generator'], $aliceOptions['private']);
+ $bob = new Crypt_DiffieHellman($bobOptions['prime'], $bobOptions['generator'], $bobOptions['private']);
+ $alice->generateKeys();
+ $bob->generateKeys();
+
+ $this->assertEquals('78', $alice->getPublicKey());
+ $this->assertEquals('534', $bob->getPublicKey());
+
+ $aliceSecretKey = $alice->computeSecretKey($bob->getPublicKey())->getSharedSecretKey();
+ $bobSecretKey = $bob->computeSecretKey($alice->getPublicKey())->getSharedSecretKey();
+
+ // both Alice and Bob should now have the same secret key
+ $this->assertEquals('117', $aliceSecretKey);
+ $this->assertEquals('117', $bobSecretKey);
+ }
+
+ public function testDiffieWithBinaryFormsAndLargeIntegers()
+ {
+ $aliceOptions = array(
+ 'prime' => '155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443',
+ 'generator'=>'2',
+ 'private' => '99209314066572595236408569591967988557141249561494267486251808035535396332278620143536317681312712891672623072630995180324388841681491857745515696789091127409515009250358965816666146342049838178521379132153348139908016819196219448310107072632515749339055798122538615135104828702523796951800575031871051678091'
+ );
+ $bobOptions = array(
+ 'prime' => '155172898181473697471232257763715539915724801966915404479707795314057629378541917580651227423698188993727816152646631438561595825688188889951272158842675419950341258706556549803580104870537681476726513255747040765857479291291572334510643245094715007229621094194349783925984760375594985848253359305585439638443',
+ 'generator'=>'2',
+ 'private' => '33411735792639558625733635717892563612548180650402161151077478314841463707948899786103588912325634730410551946772752880177868972816963551821740386700076034213408153924692562543117963464733156600545484510833072427003474207064650714831083304497737160382097083356876078146231616972608703322302585471319261275664'
+ );
+ $alice = new Crypt_DiffieHellman($aliceOptions['prime'], $aliceOptions['generator'], $aliceOptions['private']);
+ $bob = new Crypt_DiffieHellman($bobOptions['prime'], $bobOptions['generator'], $bobOptions['private']);
+ $alice->generateKeys();
+ $bob->generateKeys();
+ $this->assertEquals('0DmJUe9dr02pAtVoGyLHdC+rfBU3mDCelKGPXRDFHofx6mFfN2gcZCmp/ab4ezDXfpIBOatpVdbn2fTNUGo64DtKE2WGTsZCl90RgrGUv8XW/4WDPXeE7g5u7KWHBG/LCE5+XsilE5P5/GIyqr9gsiudTmk+H/hiYZl9Smar9k0=', base64_encode($alice->getPublicKey(Crypt_DiffieHellman::BINARY)));
+ $this->assertEquals('v8puCBaHdch0stxmkyS/sZvZHyB5f0AVkopAQ5wKSZIyEHHcGn7DXXH2u4WdCL+kMr8BcRpxRBJ0TDwfZPpu53nFNEjUd81WlfaKk95e4a/DC4dhlfBkQMebleobhedQPFAo7F9SkHN7uTLa/glxG+3T9DTb+ikcOVPoH3A1G6g=', base64_encode($bob->getPublicKey(Crypt_DiffieHellman::BINARY)));
+
+ $aliceSecretKey = $alice->computeSecretKey($bob->getPublicKey(Crypt_DiffieHellman::BINARY), Crypt_DiffieHellman::BINARY)
+ ->getSharedSecretKey(Crypt_DiffieHellman::BINARY);
+ $bobSecretKey = $bob->computeSecretKey($alice->getPublicKey(Crypt_DiffieHellman::BINARY), Crypt_DiffieHellman::BINARY)
+ ->getSharedSecretKey(Crypt_DiffieHellman::BINARY);
+
+ // both Alice and Bob should now have the same secret key
+ $expectedSharedSecret = base64_decode('FAAkw7NN1+raX9K1+dR3nqX2LZcDYYuZH13lpasaDIM4/ZXqbzdgiHZ86SILN27BjmJObtNQG/SNHfhxMalLMtLv+v0JFte/6+pIvMG9tAoPFsVh2BAvBuNpLY5W5gusgQ2p4pvJK0wz9YJ8iFdOHEOnhzYuN7LS/YXx2rBOz0Q=');
+ $this->assertEquals($expectedSharedSecret, $aliceSecretKey);
+ $this->assertEquals($expectedSharedSecret, $bobSecretKey);
+ }
+
+}
View
6 tests/TestConfiguration.php.dist
@@ -0,0 +1,6 @@
+<?php
+define('TESTS_BCMATH_ENABLED', true);
+define('TESTS_GMP_ENABLED', false);
+define('TESTS_BIGINT_ENABLED', false);
+define('TESTS_GENERATE_REPORT', false);
+define('TESTS_GENERATE_REPORT_TARGET', '/path/to/target');
View
17 tests/TestHelper.php
@@ -0,0 +1,17 @@
+<?php
+
+error_reporting( E_ALL | E_STRICT );
+date_default_timezone_set('Europe/London');
+
+$prRoot = dirname(dirname(__FILE__));
+$prTests = $prRoot . DIRECTORY_SEPARATOR . 'tests';
+
+set_include_path($prRoot . PATH_SEPARATOR
+ . $prTests . PATH_SEPARATOR
+ . get_include_path());
+
+if (is_readable($prTests . DIRECTORY_SEPARATOR . 'TestConfiguration.php')) {
+ require_once 'TestConfiguration.php';
+} else {
+ require_once 'TestConfiguration.php.dist';
+}

0 comments on commit f1da33b

Please sign in to comment.
Something went wrong with that request. Please try again.