Math.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. * @copyright Copyright (c) 2007 Pádraic Brady (http://blog.astrumfutura.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. * @version $Id: Math.php 151 2008-06-16 16:50:42Z padraic $
  20. */
  21. /** Zend_Crypt_Math_BigInteger */
  22. require_once 'Zend/Crypt/Math/BigInteger.php';
  23. class Zend_Crypt_Math extends Zend_Crypt_Math_BigInteger
  24. {
  25. /**
  26. * Generate a pseudorandom number within the given range.
  27. * Will attempt to read from a systems RNG if it exists or else utilises
  28. * a simple random character to maximum length process. Simplicity
  29. * is a factor better left for development...
  30. *
  31. * @param string|int $minimum
  32. * @param string|int $maximum
  33. * @return string
  34. */
  35. public function rand($minimum, $maximum)
  36. {
  37. if (file_exists('/dev/urandom')) {
  38. $frandom = fopen('/dev/urandom', 'r');
  39. if ($frandom !== false) {
  40. return fread($frandom, strlen($maximum) - 1);
  41. }
  42. }
  43. if (strlen($maximum) < 4) {
  44. return mt_rand($minimum, $maximum - 1);
  45. }
  46. $rand = '';
  47. $i2 = strlen($maximum) - 1;
  48. for ($i = 1;$i < $i2;$i++) {
  49. $rand .= mt_rand(0,9);
  50. }
  51. $rand .= mt_rand(0,9);
  52. return $rand;
  53. }
  54. /**
  55. * Get the big endian two's complement of a given big integer in
  56. * binary notation
  57. *
  58. * @param string $long
  59. * @return string
  60. */
  61. public function btwoc($long) {
  62. if (ord($long[0]) > 127) {
  63. return "\x00" . $long;
  64. }
  65. return $long;
  66. }
  67. /**
  68. * Translate a binary form into a big integer string
  69. *
  70. * @param string $binary
  71. * @return string
  72. */
  73. public function fromBinary($binary) {
  74. return $this->_math->binaryToInteger($binary);
  75. }
  76. /**
  77. * Translate a big integer string into a binary form
  78. *
  79. * @param string $integer
  80. * @return string
  81. */
  82. public function toBinary($integer)
  83. {
  84. return $this->_math->integerToBinary($integer);
  85. }
  86. }