PageRenderTime 62ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Zend/OpenId.php

https://bitbucket.org/acidel/buykoala
PHP | 753 lines | 600 code | 27 blank | 126 comment | 130 complexity | 6a314580f5cf9086d3841fd85f18cfde MD5 | raw file
  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_OpenId
  17. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id: OpenId.php 22653 2010-07-22 18:41:39Z mabe $
  20. */
  21. /**
  22. * @see Zend_Controller_Response_Abstract
  23. */
  24. #require_once "Zend/Controller/Response/Abstract.php";
  25. /**
  26. * Static class that contains common utility functions for
  27. * {@link Zend_OpenId_Consumer} and {@link Zend_OpenId_Provider}.
  28. *
  29. * This class implements common utility functions that are used by both
  30. * Consumer and Provider. They include functions for Diffie-Hellman keys
  31. * generation and exchange, URL normalization, HTTP redirection and some others.
  32. *
  33. * @category Zend
  34. * @package Zend_OpenId
  35. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  36. * @license http://framework.zend.com/license/new-bsd New BSD License
  37. */
  38. class Zend_OpenId
  39. {
  40. /**
  41. * Default Diffie-Hellman key generator (1024 bit)
  42. */
  43. const DH_P = 'dcf93a0b883972ec0e19989ac5a2ce310e1d37717e8d9571bb7623731866e61ef75a2e27898b057f9891c2e27a639c3f29b60814581cd3b2ca3986d2683705577d45c2e7e52dc81c7a171876e5cea74b1448bfdfaf18828efd2519f14e45e3826634af1949e5b535cc829a483b8a76223e5d490a257f05bdff16f2fb22c583ab';
  44. /**
  45. * Default Diffie-Hellman prime number (should be 2 or 5)
  46. */
  47. const DH_G = '02';
  48. /**
  49. * OpenID 2.0 namespace. All OpenID 2.0 messages MUST contain variable
  50. * openid.ns with its value.
  51. */
  52. const NS_2_0 = 'http://specs.openid.net/auth/2.0';
  53. /**
  54. * Allows enable/disable stoping execution of PHP script after redirect()
  55. */
  56. static public $exitOnRedirect = true;
  57. /**
  58. * Alternative request URL that can be used to override the default
  59. * selfUrl() response
  60. */
  61. static public $selfUrl = null;
  62. /**
  63. * Sets alternative request URL that can be used to override the default
  64. * selfUrl() response
  65. *
  66. * @param string $selfUrl the URL to be set
  67. * @return string the old value of overriding URL
  68. */
  69. static public function setSelfUrl($selfUrl = null)
  70. {
  71. $ret = self::$selfUrl;
  72. self::$selfUrl = $selfUrl;
  73. return $ret;
  74. }
  75. /**
  76. * Returns a full URL that was requested on current HTTP request.
  77. *
  78. * @return string
  79. */
  80. static public function selfUrl()
  81. {
  82. if (self::$selfUrl !== null) {
  83. return self::$selfUrl;
  84. } if (isset($_SERVER['SCRIPT_URI'])) {
  85. return $_SERVER['SCRIPT_URI'];
  86. }
  87. $url = '';
  88. $port = '';
  89. if (isset($_SERVER['HTTP_HOST'])) {
  90. if (($pos = strpos($_SERVER['HTTP_HOST'], ':')) === false) {
  91. if (isset($_SERVER['SERVER_PORT'])) {
  92. $port = ':' . $_SERVER['SERVER_PORT'];
  93. }
  94. $url = $_SERVER['HTTP_HOST'];
  95. } else {
  96. $url = substr($_SERVER['HTTP_HOST'], 0, $pos);
  97. $port = substr($_SERVER['HTTP_HOST'], $pos);
  98. }
  99. } else if (isset($_SERVER['SERVER_NAME'])) {
  100. $url = $_SERVER['SERVER_NAME'];
  101. if (isset($_SERVER['SERVER_PORT'])) {
  102. $port = ':' . $_SERVER['SERVER_PORT'];
  103. }
  104. }
  105. if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
  106. $url = 'https://' . $url;
  107. if ($port == ':443') {
  108. $port = '';
  109. }
  110. } else {
  111. $url = 'http://' . $url;
  112. if ($port == ':80') {
  113. $port = '';
  114. }
  115. }
  116. $url .= $port;
  117. if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
  118. $url .= $_SERVER['HTTP_X_REWRITE_URL'];
  119. } elseif (isset($_SERVER['REQUEST_URI'])) {
  120. $query = strpos($_SERVER['REQUEST_URI'], '?');
  121. if ($query === false) {
  122. $url .= $_SERVER['REQUEST_URI'];
  123. } else {
  124. $url .= substr($_SERVER['REQUEST_URI'], 0, $query);
  125. }
  126. } else if (isset($_SERVER['SCRIPT_URL'])) {
  127. $url .= $_SERVER['SCRIPT_URL'];
  128. } else if (isset($_SERVER['REDIRECT_URL'])) {
  129. $url .= $_SERVER['REDIRECT_URL'];
  130. } else if (isset($_SERVER['PHP_SELF'])) {
  131. $url .= $_SERVER['PHP_SELF'];
  132. } else if (isset($_SERVER['SCRIPT_NAME'])) {
  133. $url .= $_SERVER['SCRIPT_NAME'];
  134. if (isset($_SERVER['PATH_INFO'])) {
  135. $url .= $_SERVER['PATH_INFO'];
  136. }
  137. }
  138. return $url;
  139. }
  140. /**
  141. * Returns an absolute URL for the given one
  142. *
  143. * @param string $url absilute or relative URL
  144. * @return string
  145. */
  146. static public function absoluteUrl($url)
  147. {
  148. if (empty($url)) {
  149. return Zend_OpenId::selfUrl();
  150. } else if (!preg_match('|^([^:]+)://|', $url)) {
  151. if (preg_match('|^([^:]+)://([^:@]*(?:[:][^@]*)?@)?([^/:@?#]*)(?:[:]([^/?#]*))?(/[^?]*)?((?:[?](?:[^#]*))?(?:#.*)?)$|', Zend_OpenId::selfUrl(), $reg)) {
  152. $scheme = $reg[1];
  153. $auth = $reg[2];
  154. $host = $reg[3];
  155. $port = $reg[4];
  156. $path = $reg[5];
  157. $query = $reg[6];
  158. if ($url[0] == '/') {
  159. return $scheme
  160. . '://'
  161. . $auth
  162. . $host
  163. . (empty($port) ? '' : (':' . $port))
  164. . $url;
  165. } else {
  166. $dir = dirname($path);
  167. return $scheme
  168. . '://'
  169. . $auth
  170. . $host
  171. . (empty($port) ? '' : (':' . $port))
  172. . (strlen($dir) > 1 ? $dir : '')
  173. . '/'
  174. . $url;
  175. }
  176. }
  177. }
  178. return $url;
  179. }
  180. /**
  181. * Converts variable/value pairs into URL encoded query string
  182. *
  183. * @param array $params variable/value pairs
  184. * @return string URL encoded query string
  185. */
  186. static public function paramsToQuery($params)
  187. {
  188. foreach($params as $key => $value) {
  189. if (isset($query)) {
  190. $query .= '&' . $key . '=' . urlencode($value);
  191. } else {
  192. $query = $key . '=' . urlencode($value);
  193. }
  194. }
  195. return isset($query) ? $query : '';
  196. }
  197. /**
  198. * Normalizes URL according to RFC 3986 to use it in comparison operations.
  199. * The function gets URL argument by reference and modifies it.
  200. * It returns true on success and false of failure.
  201. *
  202. * @param string &$id url to be normalized
  203. * @return bool
  204. */
  205. static public function normalizeUrl(&$id)
  206. {
  207. // RFC 3986, 6.2.2. Syntax-Based Normalization
  208. // RFC 3986, 6.2.2.2 Percent-Encoding Normalization
  209. $i = 0;
  210. $n = strlen($id);
  211. $res = '';
  212. while ($i < $n) {
  213. if ($id[$i] == '%') {
  214. if ($i + 2 >= $n) {
  215. return false;
  216. }
  217. ++$i;
  218. if ($id[$i] >= '0' && $id[$i] <= '9') {
  219. $c = ord($id[$i]) - ord('0');
  220. } else if ($id[$i] >= 'A' && $id[$i] <= 'F') {
  221. $c = ord($id[$i]) - ord('A') + 10;
  222. } else if ($id[$i] >= 'a' && $id[$i] <= 'f') {
  223. $c = ord($id[$i]) - ord('a') + 10;
  224. } else {
  225. return false;
  226. }
  227. ++$i;
  228. if ($id[$i] >= '0' && $id[$i] <= '9') {
  229. $c = ($c << 4) | (ord($id[$i]) - ord('0'));
  230. } else if ($id[$i] >= 'A' && $id[$i] <= 'F') {
  231. $c = ($c << 4) | (ord($id[$i]) - ord('A') + 10);
  232. } else if ($id[$i] >= 'a' && $id[$i] <= 'f') {
  233. $c = ($c << 4) | (ord($id[$i]) - ord('a') + 10);
  234. } else {
  235. return false;
  236. }
  237. ++$i;
  238. $ch = chr($c);
  239. if (($ch >= 'A' && $ch <= 'Z') ||
  240. ($ch >= 'a' && $ch <= 'z') ||
  241. $ch == '-' ||
  242. $ch == '.' ||
  243. $ch == '_' ||
  244. $ch == '~') {
  245. $res .= $ch;
  246. } else {
  247. $res .= '%';
  248. if (($c >> 4) < 10) {
  249. $res .= chr(($c >> 4) + ord('0'));
  250. } else {
  251. $res .= chr(($c >> 4) - 10 + ord('A'));
  252. }
  253. $c = $c & 0xf;
  254. if ($c < 10) {
  255. $res .= chr($c + ord('0'));
  256. } else {
  257. $res .= chr($c - 10 + ord('A'));
  258. }
  259. }
  260. } else {
  261. $res .= $id[$i++];
  262. }
  263. }
  264. if (!preg_match('|^([^:]+)://([^:@]*(?:[:][^@]*)?@)?([^/:@?#]*)(?:[:]([^/?#]*))?(/[^?#]*)?((?:[?](?:[^#]*))?)((?:#.*)?)$|', $res, $reg)) {
  265. return false;
  266. }
  267. $scheme = $reg[1];
  268. $auth = $reg[2];
  269. $host = $reg[3];
  270. $port = $reg[4];
  271. $path = $reg[5];
  272. $query = $reg[6];
  273. $fragment = $reg[7]; /* strip it */
  274. if (empty($scheme) || empty($host)) {
  275. return false;
  276. }
  277. // RFC 3986, 6.2.2.1. Case Normalization
  278. $scheme = strtolower($scheme);
  279. $host = strtolower($host);
  280. // RFC 3986, 6.2.2.3. Path Segment Normalization
  281. if (!empty($path)) {
  282. $i = 0;
  283. $n = strlen($path);
  284. $res = "";
  285. while ($i < $n) {
  286. if ($path[$i] == '/') {
  287. ++$i;
  288. while ($i < $n && $path[$i] == '/') {
  289. ++$i;
  290. }
  291. if ($i < $n && $path[$i] == '.') {
  292. ++$i;
  293. if ($i < $n && $path[$i] == '.') {
  294. ++$i;
  295. if ($i == $n || $path[$i] == '/') {
  296. if (($pos = strrpos($res, '/')) !== false) {
  297. $res = substr($res, 0, $pos);
  298. }
  299. } else {
  300. $res .= '/..';
  301. }
  302. } else if ($i != $n && $path[$i] != '/') {
  303. $res .= '/.';
  304. }
  305. } else {
  306. $res .= '/';
  307. }
  308. } else {
  309. $res .= $path[$i++];
  310. }
  311. }
  312. $path = $res;
  313. }
  314. // RFC 3986,6.2.3. Scheme-Based Normalization
  315. if ($scheme == 'http') {
  316. if ($port == 80) {
  317. $port = '';
  318. }
  319. } else if ($scheme == 'https') {
  320. if ($port == 443) {
  321. $port = '';
  322. }
  323. }
  324. if (empty($path)) {
  325. $path = '/';
  326. }
  327. $id = $scheme
  328. . '://'
  329. . $auth
  330. . $host
  331. . (empty($port) ? '' : (':' . $port))
  332. . $path
  333. . $query;
  334. return true;
  335. }
  336. /**
  337. * Normalizes OpenID identifier that can be URL or XRI name.
  338. * Returns true on success and false of failure.
  339. *
  340. * Normalization is performed according to the following rules:
  341. * 1. If the user's input starts with one of the "xri://", "xri://$ip*",
  342. * or "xri://$dns*" prefixes, they MUST be stripped off, so that XRIs
  343. * are used in the canonical form, and URI-authority XRIs are further
  344. * considered URL identifiers.
  345. * 2. If the first character of the resulting string is an XRI Global
  346. * Context Symbol ("=", "@", "+", "$", "!"), then the input SHOULD be
  347. * treated as an XRI.
  348. * 3. Otherwise, the input SHOULD be treated as an http URL; if it does
  349. * not include a "http" or "https" scheme, the Identifier MUST be
  350. * prefixed with the string "http://".
  351. * 4. URL identifiers MUST then be further normalized by both following
  352. * redirects when retrieving their content and finally applying the
  353. * rules in Section 6 of [RFC3986] to the final destination URL.
  354. * @param string &$id identifier to be normalized
  355. * @return bool
  356. */
  357. static public function normalize(&$id)
  358. {
  359. $id = trim($id);
  360. if (strlen($id) === 0) {
  361. return true;
  362. }
  363. // 7.2.1
  364. if (strpos($id, 'xri://$ip*') === 0) {
  365. $id = substr($id, strlen('xri://$ip*'));
  366. } else if (strpos($id, 'xri://$dns*') === 0) {
  367. $id = substr($id, strlen('xri://$dns*'));
  368. } else if (strpos($id, 'xri://') === 0) {
  369. $id = substr($id, strlen('xri://'));
  370. }
  371. // 7.2.2
  372. if ($id[0] == '=' ||
  373. $id[0] == '@' ||
  374. $id[0] == '+' ||
  375. $id[0] == '$' ||
  376. $id[0] == '!') {
  377. return true;
  378. }
  379. // 7.2.3
  380. if (strpos($id, "://") === false) {
  381. $id = 'http://' . $id;
  382. }
  383. // 7.2.4
  384. return self::normalizeURL($id);
  385. }
  386. /**
  387. * Performs a HTTP redirection to specified URL with additional data.
  388. * It may generate redirected request using GET or POST HTTP method.
  389. * The function never returns.
  390. *
  391. * @param string $url URL to redirect to
  392. * @param array $params additional variable/value pairs to send
  393. * @param Zend_Controller_Response_Abstract $response
  394. * @param string $method redirection method ('GET' or 'POST')
  395. */
  396. static public function redirect($url, $params = null,
  397. Zend_Controller_Response_Abstract $response = null, $method = 'GET')
  398. {
  399. $url = Zend_OpenId::absoluteUrl($url);
  400. $body = "";
  401. if (null === $response) {
  402. #require_once "Zend/Controller/Response/Http.php";
  403. $response = new Zend_Controller_Response_Http();
  404. }
  405. if ($method == 'POST') {
  406. $body = "<html><body onLoad=\"document.forms[0].submit();\">\n";
  407. $body .= "<form method=\"POST\" action=\"$url\">\n";
  408. if (is_array($params) && count($params) > 0) {
  409. foreach($params as $key => $value) {
  410. $body .= '<input type="hidden" name="' . $key . '" value="' . $value . "\">\n";
  411. }
  412. }
  413. $body .= "<input type=\"submit\" value=\"Continue OpenID transaction\">\n";
  414. $body .= "</form></body></html>\n";
  415. } else if (is_array($params) && count($params) > 0) {
  416. if (strpos($url, '?') === false) {
  417. $url .= '?' . self::paramsToQuery($params);
  418. } else {
  419. $url .= '&' . self::paramsToQuery($params);
  420. }
  421. }
  422. if (!empty($body)) {
  423. $response->setBody($body);
  424. } else if (!$response->canSendHeaders()) {
  425. $response->setBody("<script language=\"JavaScript\"" .
  426. " type=\"text/javascript\">window.location='$url';" .
  427. "</script>");
  428. } else {
  429. $response->setRedirect($url);
  430. }
  431. $response->sendResponse();
  432. if (self::$exitOnRedirect) {
  433. exit();
  434. }
  435. }
  436. /**
  437. * Produces string of random byte of given length.
  438. *
  439. * @param integer $len length of requested string
  440. * @return string RAW random binary string
  441. */
  442. static public function randomBytes($len)
  443. {
  444. $key = '';
  445. for($i=0; $i < $len; $i++) {
  446. $key .= chr(mt_rand(0, 255));
  447. }
  448. return $key;
  449. }
  450. /**
  451. * Generates a hash value (message digest) according to given algorithm.
  452. * It returns RAW binary string.
  453. *
  454. * This is a wrapper function that uses one of available internal function
  455. * dependent on given PHP configuration. It may use various functions from
  456. * ext/openssl, ext/hash, ext/mhash or ext/standard.
  457. *
  458. * @param string $func digest algorithm
  459. * @param string $data data to sign
  460. * @return string RAW digital signature
  461. * @throws Zend_OpenId_Exception
  462. */
  463. static public function digest($func, $data)
  464. {
  465. if (function_exists('openssl_digest')) {
  466. return openssl_digest($data, $func, true);
  467. } else if (function_exists('hash')) {
  468. return hash($func, $data, true);
  469. } else if ($func === 'sha1') {
  470. return sha1($data, true);
  471. } else if ($func === 'sha256') {
  472. if (function_exists('mhash')) {
  473. return mhash(MHASH_SHA256 , $data);
  474. }
  475. }
  476. #require_once "Zend/OpenId/Exception.php";
  477. throw new Zend_OpenId_Exception(
  478. 'Unsupported digest algorithm "' . $func . '".',
  479. Zend_OpenId_Exception::UNSUPPORTED_DIGEST);
  480. }
  481. /**
  482. * Generates a keyed hash value using the HMAC method. It uses ext/hash
  483. * if available or user-level PHP implementation, that is not significantly
  484. * slower.
  485. *
  486. * @param string $macFunc name of selected hashing algorithm (sha1, sha256)
  487. * @param string $data data to sign
  488. * @param string $secret shared secret key used for generating the HMAC
  489. * variant of the message digest
  490. * @return string RAW HMAC value
  491. */
  492. static public function hashHmac($macFunc, $data, $secret)
  493. {
  494. // #require_once "Zend/Crypt/Hmac.php";
  495. // return Zend_Crypt_Hmac::compute($secret, $macFunc, $data, Zend_Crypt_Hmac::BINARY);
  496. if (function_exists('hash_hmac')) {
  497. return hash_hmac($macFunc, $data, $secret, 1);
  498. } else {
  499. if (Zend_OpenId::strlen($secret) > 64) {
  500. $secret = self::digest($macFunc, $secret);
  501. }
  502. $secret = str_pad($secret, 64, chr(0x00));
  503. $ipad = str_repeat(chr(0x36), 64);
  504. $opad = str_repeat(chr(0x5c), 64);
  505. $hash1 = self::digest($macFunc, ($secret ^ $ipad) . $data);
  506. return self::digest($macFunc, ($secret ^ $opad) . $hash1);
  507. }
  508. }
  509. /**
  510. * Converts binary representation into ext/gmp or ext/bcmath big integer
  511. * representation.
  512. *
  513. * @param string $bin binary representation of big number
  514. * @return mixed
  515. * @throws Zend_OpenId_Exception
  516. */
  517. static protected function binToBigNum($bin)
  518. {
  519. if (extension_loaded('gmp')) {
  520. return gmp_init(bin2hex($bin), 16);
  521. } else if (extension_loaded('bcmath')) {
  522. $bn = 0;
  523. $len = Zend_OpenId::strlen($bin);
  524. for ($i = 0; $i < $len; $i++) {
  525. $bn = bcmul($bn, 256);
  526. $bn = bcadd($bn, ord($bin[$i]));
  527. }
  528. return $bn;
  529. }
  530. #require_once "Zend/OpenId/Exception.php";
  531. throw new Zend_OpenId_Exception(
  532. 'The system doesn\'t have proper big integer extension',
  533. Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH);
  534. }
  535. /**
  536. * Converts internal ext/gmp or ext/bcmath big integer representation into
  537. * binary string.
  538. *
  539. * @param mixed $bn big number
  540. * @return string
  541. * @throws Zend_OpenId_Exception
  542. */
  543. static protected function bigNumToBin($bn)
  544. {
  545. if (extension_loaded('gmp')) {
  546. $s = gmp_strval($bn, 16);
  547. if (strlen($s) % 2 != 0) {
  548. $s = '0' . $s;
  549. } else if ($s[0] > '7') {
  550. $s = '00' . $s;
  551. }
  552. return pack("H*", $s);
  553. } else if (extension_loaded('bcmath')) {
  554. $cmp = bccomp($bn, 0);
  555. if ($cmp == 0) {
  556. return "\0";
  557. } else if ($cmp < 0) {
  558. #require_once "Zend/OpenId/Exception.php";
  559. throw new Zend_OpenId_Exception(
  560. 'Big integer arithmetic error',
  561. Zend_OpenId_Exception::ERROR_LONG_MATH);
  562. }
  563. $bin = "";
  564. while (bccomp($bn, 0) > 0) {
  565. $bin = chr(bcmod($bn, 256)) . $bin;
  566. $bn = bcdiv($bn, 256);
  567. }
  568. if (ord($bin[0]) > 127) {
  569. $bin = "\0" . $bin;
  570. }
  571. return $bin;
  572. }
  573. #require_once "Zend/OpenId/Exception.php";
  574. throw new Zend_OpenId_Exception(
  575. 'The system doesn\'t have proper big integer extension',
  576. Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH);
  577. }
  578. /**
  579. * Performs the first step of a Diffie-Hellman key exchange by generating
  580. * private and public DH values based on given prime number $p and
  581. * generator $g. Both sides of key exchange MUST have the same prime number
  582. * and generator. In this case they will able to create a random shared
  583. * secret that is never send from one to the other.
  584. *
  585. * @param string $p prime number in binary representation
  586. * @param string $g generator in binary representation
  587. * @param string $priv_key private key in binary representation
  588. * @return mixed
  589. */
  590. static public function createDhKey($p, $g, $priv_key = null)
  591. {
  592. if (function_exists('openssl_dh_compute_key')) {
  593. $dh_details = array(
  594. 'p' => $p,
  595. 'g' => $g
  596. );
  597. if ($priv_key !== null) {
  598. $dh_details['priv_key'] = $priv_key;
  599. }
  600. return openssl_pkey_new(array('dh'=>$dh_details));
  601. } else {
  602. $bn_p = self::binToBigNum($p);
  603. $bn_g = self::binToBigNum($g);
  604. if ($priv_key === null) {
  605. $priv_key = self::randomBytes(Zend_OpenId::strlen($p));
  606. }
  607. $bn_priv_key = self::binToBigNum($priv_key);
  608. if (extension_loaded('gmp')) {
  609. $bn_pub_key = gmp_powm($bn_g, $bn_priv_key, $bn_p);
  610. } else if (extension_loaded('bcmath')) {
  611. $bn_pub_key = bcpowmod($bn_g, $bn_priv_key, $bn_p);
  612. }
  613. $pub_key = self::bigNumToBin($bn_pub_key);
  614. return array(
  615. 'p' => $bn_p,
  616. 'g' => $bn_g,
  617. 'priv_key' => $bn_priv_key,
  618. 'pub_key' => $bn_pub_key,
  619. 'details' => array(
  620. 'p' => $p,
  621. 'g' => $g,
  622. 'priv_key' => $priv_key,
  623. 'pub_key' => $pub_key));
  624. }
  625. }
  626. /**
  627. * Returns an associative array with Diffie-Hellman key components in
  628. * binary representation. The array includes original prime number 'p' and
  629. * generator 'g', random private key 'priv_key' and corresponding public
  630. * key 'pub_key'.
  631. *
  632. * @param mixed $dh Diffie-Hellman key
  633. * @return array
  634. */
  635. static public function getDhKeyDetails($dh)
  636. {
  637. if (function_exists('openssl_dh_compute_key')) {
  638. $details = openssl_pkey_get_details($dh);
  639. if (isset($details['dh'])) {
  640. return $details['dh'];
  641. }
  642. } else {
  643. return $dh['details'];
  644. }
  645. }
  646. /**
  647. * Computes the shared secret from the private DH value $dh and the other
  648. * party's public value in $pub_key
  649. *
  650. * @param string $pub_key other party's public value
  651. * @param mixed $dh Diffie-Hellman key
  652. * @return string
  653. * @throws Zend_OpenId_Exception
  654. */
  655. static public function computeDhSecret($pub_key, $dh)
  656. {
  657. if (function_exists('openssl_dh_compute_key')) {
  658. $ret = openssl_dh_compute_key($pub_key, $dh);
  659. if (ord($ret[0]) > 127) {
  660. $ret = "\0" . $ret;
  661. }
  662. return $ret;
  663. } else if (extension_loaded('gmp')) {
  664. $bn_pub_key = self::binToBigNum($pub_key);
  665. $bn_secret = gmp_powm($bn_pub_key, $dh['priv_key'], $dh['p']);
  666. return self::bigNumToBin($bn_secret);
  667. } else if (extension_loaded('bcmath')) {
  668. $bn_pub_key = self::binToBigNum($pub_key);
  669. $bn_secret = bcpowmod($bn_pub_key, $dh['priv_key'], $dh['p']);
  670. return self::bigNumToBin($bn_secret);
  671. }
  672. #require_once "Zend/OpenId/Exception.php";
  673. throw new Zend_OpenId_Exception(
  674. 'The system doesn\'t have proper big integer extension',
  675. Zend_OpenId_Exception::UNSUPPORTED_LONG_MATH);
  676. }
  677. /**
  678. * Takes an arbitrary precision integer and returns its shortest big-endian
  679. * two's complement representation.
  680. *
  681. * Arbitrary precision integers MUST be encoded as big-endian signed two's
  682. * complement binary strings. Henceforth, "btwoc" is a function that takes
  683. * an arbitrary precision integer and returns its shortest big-endian two's
  684. * complement representation. All integers that are used with
  685. * Diffie-Hellman Key Exchange are positive. This means that the left-most
  686. * bit of the two's complement representation MUST be zero. If it is not,
  687. * implementations MUST add a zero byte at the front of the string.
  688. *
  689. * @param string $str binary representation of arbitrary precision integer
  690. * @return string big-endian signed representation
  691. */
  692. static public function btwoc($str)
  693. {
  694. if (ord($str[0]) > 127) {
  695. return "\0" . $str;
  696. }
  697. return $str;
  698. }
  699. /**
  700. * Returns lenght of binary string in bytes
  701. *
  702. * @param string $str
  703. * @return int the string lenght
  704. */
  705. static public function strlen($str)
  706. {
  707. if (extension_loaded('mbstring') &&
  708. (((int)ini_get('mbstring.func_overload')) & 2)) {
  709. return mb_strlen($str, 'latin1');
  710. } else {
  711. return strlen($str);
  712. }
  713. }
  714. }