PageRenderTime 53ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Zend/OpenId.php

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