DiffieHellman.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Crypt
  17. * @subpackage DiffieHellman
  18. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * PHP implementation of the Diffie-Hellman public key encryption algorithm.
  24. * Allows two unassociated parties to establish a joint shared secret key
  25. * to be used in encrypting subsequent communications.
  26. *
  27. * @category Zend
  28. * @package Zend_Crypt
  29. * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
  30. * @license http://framework.zend.com/license/new-bsd New BSD License
  31. */
  32. class Zend_Crypt_DiffieHellman
  33. {
  34. /**
  35. * Static flag to select whether to use PHP5.3's openssl extension
  36. * if available.
  37. *
  38. * @var boolean
  39. */
  40. public static $useOpenssl = true;
  41. /**
  42. * Default large prime number; required by the algorithm.
  43. *
  44. * @var string
  45. */
  46. private $_prime = null;
  47. /**
  48. * The default generator number. This number must be greater than 0 but
  49. * less than the prime number set.
  50. *
  51. * @var string
  52. */
  53. private $_generator = null;
  54. /**
  55. * A private number set by the local user. It's optional and will
  56. * be generated if not set.
  57. *
  58. * @var string
  59. */
  60. private $_privateKey = null;
  61. /**
  62. * BigInteger support object courtesy of Zend_Crypt_Math
  63. *
  64. * @var Zend_Crypt_Math_BigInteger
  65. */
  66. private $_math = null;
  67. /**
  68. * The public key generated by this instance after calling generateKeys().
  69. *
  70. * @var string
  71. */
  72. private $_publicKey = null;
  73. /**
  74. * The shared secret key resulting from a completed Diffie Hellman
  75. * exchange
  76. *
  77. * @var string
  78. */
  79. private $_secretKey = null;
  80. /**
  81. * Constants
  82. */
  83. const BINARY = 'binary';
  84. const NUMBER = 'number';
  85. const BTWOC = 'btwoc';
  86. /**
  87. * Constructor; if set construct the object using the parameter array to
  88. * set values for Prime, Generator and Private.
  89. * If a Private Key is not set, one will be generated at random.
  90. *
  91. * @param string $prime
  92. * @param string $generator
  93. * @param string $privateKey
  94. * @param string $privateKeyType
  95. */
  96. public function __construct($prime, $generator, $privateKey = null, $privateKeyType = self::NUMBER)
  97. {
  98. $this->setPrime($prime);
  99. $this->setGenerator($generator);
  100. if ($privateKey !== null) {
  101. $this->setPrivateKey($privateKey, $privateKeyType);
  102. }
  103. $this->setBigIntegerMath();
  104. }
  105. /**
  106. * Generate own public key. If a private number has not already been
  107. * set, one will be generated at this stage.
  108. *
  109. * @return Zend_Crypt_DiffieHellman
  110. */
  111. public function generateKeys()
  112. {
  113. if (function_exists('openssl_dh_compute_key') && self::$useOpenssl !== false) {
  114. $details = array();
  115. $details['p'] = $this->getPrime();
  116. $details['g'] = $this->getGenerator();
  117. if ($this->hasPrivateKey()) {
  118. $details['priv_key'] = $this->getPrivateKey();
  119. }
  120. $opensslKeyResource = openssl_pkey_new( array('dh' => $details) );
  121. $data = openssl_pkey_get_details($opensslKeyResource);
  122. $this->setPrivateKey($data['dh']['priv_key'], self::BINARY);
  123. $this->setPublicKey($data['dh']['pub_key'], self::BINARY);
  124. } else {
  125. // Private key is lazy generated in the absence of PHP 5.3's ext/openssl
  126. $publicKey = $this->_math->powmod($this->getGenerator(), $this->getPrivateKey(), $this->getPrime());
  127. $this->setPublicKey($publicKey);
  128. }
  129. return $this;
  130. }
  131. /**
  132. * Setter for the value of the public number
  133. *
  134. * @param string $number
  135. * @param string $type
  136. * @throws Zend_Crypt_DiffieHellman_Exception
  137. * @return Zend_Crypt_DiffieHellman
  138. */
  139. public function setPublicKey($number, $type = self::NUMBER)
  140. {
  141. if ($type == self::BINARY) {
  142. $number = $this->_math->fromBinary($number);
  143. }
  144. if (!preg_match("/^\d+$/", $number)) {
  145. #require_once('Zend/Crypt/DiffieHellman/Exception.php');
  146. throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number');
  147. }
  148. $this->_publicKey = (string) $number;
  149. return $this;
  150. }
  151. /**
  152. * Returns own public key for communication to the second party to this
  153. * transaction.
  154. *
  155. * @param string $type
  156. * @throws Zend_Crypt_DiffieHellman_Exception
  157. * @return string
  158. */
  159. public function getPublicKey($type = self::NUMBER)
  160. {
  161. if ($this->_publicKey === null) {
  162. #require_once 'Zend/Crypt/DiffieHellman/Exception.php';
  163. throw new Zend_Crypt_DiffieHellman_Exception('A public key has not yet been generated using a prior call to generateKeys()');
  164. }
  165. if ($type == self::BINARY) {
  166. return $this->_math->toBinary($this->_publicKey);
  167. } elseif ($type == self::BTWOC) {
  168. return $this->_math->btwoc($this->_math->toBinary($this->_publicKey));
  169. }
  170. return $this->_publicKey;
  171. }
  172. /**
  173. * Compute the shared secret key based on the public key received from the
  174. * the second party to this transaction. This should agree to the secret
  175. * key the second party computes on our own public key.
  176. * Once in agreement, the key is known to only to both parties.
  177. * By default, the function expects the public key to be in binary form
  178. * which is the typical format when being transmitted.
  179. *
  180. * If you need the binary form of the shared secret key, call
  181. * getSharedSecretKey() with the optional parameter for Binary output.
  182. *
  183. * @param string $publicKey
  184. * @param string $type
  185. * @param string $output
  186. * @throws Zend_Crypt_DiffieHellman_Exception
  187. * @return mixed
  188. */
  189. public function computeSecretKey($publicKey, $type = self::NUMBER, $output = self::NUMBER)
  190. {
  191. if ($type == self::BINARY) {
  192. $publicKey = $this->_math->fromBinary($publicKey);
  193. }
  194. if (!preg_match("/^\d+$/", $publicKey)) {
  195. #require_once('Zend/Crypt/DiffieHellman/Exception.php');
  196. throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number');
  197. }
  198. if (function_exists('openssl_dh_compute_key') && self::$useOpenssl !== false) {
  199. $this->_secretKey = openssl_dh_compute_key($publicKey, $this->getPublicKey());
  200. } else {
  201. $this->_secretKey = $this->_math->powmod($publicKey, $this->getPrivateKey(), $this->getPrime());
  202. }
  203. return $this->getSharedSecretKey($output);
  204. }
  205. /**
  206. * Return the computed shared secret key from the DiffieHellman transaction
  207. *
  208. * @param string $type
  209. * @throws Zend_Crypt_DiffieHellman_Exception
  210. * @return string
  211. */
  212. public function getSharedSecretKey($type = self::NUMBER)
  213. {
  214. if (!isset($this->_secretKey)) {
  215. #require_once('Zend/Crypt/DiffieHellman/Exception.php');
  216. throw new Zend_Crypt_DiffieHellman_Exception('A secret key has not yet been computed; call computeSecretKey()');
  217. }
  218. if ($type == self::BINARY) {
  219. return $this->_math->toBinary($this->_secretKey);
  220. } elseif ($type == self::BTWOC) {
  221. return $this->_math->btwoc($this->_math->toBinary($this->_secretKey));
  222. }
  223. return $this->_secretKey;
  224. }
  225. /**
  226. * Setter for the value of the prime number
  227. *
  228. * @param string $number
  229. * @throws Zend_Crypt_DiffieHellman_Exception
  230. * @return Zend_Crypt_DiffieHellman
  231. */
  232. public function setPrime($number)
  233. {
  234. if (!preg_match("/^\d+$/", $number) || $number < 11) {
  235. #require_once('Zend/Crypt/DiffieHellman/Exception.php');
  236. throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number or too small: should be a large natural number prime');
  237. }
  238. $this->_prime = (string) $number;
  239. return $this;
  240. }
  241. /**
  242. * Getter for the value of the prime number
  243. *
  244. * @throws Zend_Crypt_DiffieHellman_Exception
  245. * @return string
  246. */
  247. public function getPrime()
  248. {
  249. if (!isset($this->_prime)) {
  250. #require_once('Zend/Crypt/DiffieHellman/Exception.php');
  251. throw new Zend_Crypt_DiffieHellman_Exception('No prime number has been set');
  252. }
  253. return $this->_prime;
  254. }
  255. /**
  256. * Setter for the value of the generator number
  257. *
  258. * @param string $number
  259. * @throws Zend_Crypt_DiffieHellman_Exception
  260. * @return Zend_Crypt_DiffieHellman
  261. */
  262. public function setGenerator($number)
  263. {
  264. if (!preg_match("/^\d+$/", $number) || $number < 2) {
  265. #require_once('Zend/Crypt/DiffieHellman/Exception.php');
  266. throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number greater than 1');
  267. }
  268. $this->_generator = (string) $number;
  269. return $this;
  270. }
  271. /**
  272. * Getter for the value of the generator number
  273. *
  274. * @throws Zend_Crypt_DiffieHellman_Exception
  275. * @return string
  276. */
  277. public function getGenerator()
  278. {
  279. if (!isset($this->_generator)) {
  280. #require_once('Zend/Crypt/DiffieHellman/Exception.php');
  281. throw new Zend_Crypt_DiffieHellman_Exception('No generator number has been set');
  282. }
  283. return $this->_generator;
  284. }
  285. /**
  286. * Setter for the value of the private number
  287. *
  288. * @param string $number
  289. * @param string $type
  290. * @throws Zend_Crypt_DiffieHellman_Exception
  291. * @return Zend_Crypt_DiffieHellman
  292. */
  293. public function setPrivateKey($number, $type = self::NUMBER)
  294. {
  295. if ($type == self::BINARY) {
  296. $number = $this->_math->fromBinary($number);
  297. }
  298. if (!preg_match("/^\d+$/", $number)) {
  299. #require_once('Zend/Crypt/DiffieHellman/Exception.php');
  300. throw new Zend_Crypt_DiffieHellman_Exception('invalid parameter; not a positive natural number');
  301. }
  302. $this->_privateKey = (string) $number;
  303. return $this;
  304. }
  305. /**
  306. * Getter for the value of the private number
  307. *
  308. * @param string $type
  309. * @return string
  310. */
  311. public function getPrivateKey($type = self::NUMBER)
  312. {
  313. if (!$this->hasPrivateKey()) {
  314. $this->setPrivateKey($this->_generatePrivateKey(), self::BINARY);
  315. }
  316. if ($type == self::BINARY) {
  317. return $this->_math->toBinary($this->_privateKey);
  318. } elseif ($type == self::BTWOC) {
  319. return $this->_math->btwoc($this->_math->toBinary($this->_privateKey));
  320. }
  321. return $this->_privateKey;
  322. }
  323. /**
  324. * Check whether a private key currently exists.
  325. *
  326. * @return boolean
  327. */
  328. public function hasPrivateKey()
  329. {
  330. return isset($this->_privateKey);
  331. }
  332. /**
  333. * Setter to pass an extension parameter which is used to create
  334. * a specific BigInteger instance for a specific extension type.
  335. * Allows manual setting of the class in case of an extension
  336. * problem or bug.
  337. *
  338. * @param string $extension
  339. * @return void
  340. */
  341. public function setBigIntegerMath($extension = null)
  342. {
  343. /**
  344. * @see Zend_Crypt_Math
  345. */
  346. #require_once 'Zend/Crypt/Math.php';
  347. $this->_math = new Zend_Crypt_Math($extension);
  348. }
  349. /**
  350. * In the event a private number/key has not been set by the user,
  351. * or generated by ext/openssl, a best attempt will be made to
  352. * generate a random key. Having a random number generator installed
  353. * on linux/bsd is highly recommended! The alternative is not recommended
  354. * for production unless without any other option.
  355. *
  356. * @return string
  357. */
  358. protected function _generatePrivateKey()
  359. {
  360. $rand = $this->_math->rand($this->getGenerator(), $this->getPrime());
  361. return $rand;
  362. }
  363. }