serversalt.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. /**
  3. * ZeroBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.22
  11. */
  12. /**
  13. * serversalt
  14. *
  15. * This is a random string which is unique to each ZeroBin installation.
  16. * It is automatically created if not present.
  17. *
  18. * Salt is used:
  19. * - to generate unique VizHash in discussions (which are not reproductible across ZeroBin servers)
  20. * - to generate unique deletion token (which are not re-usable across ZeroBin servers)
  21. */
  22. class serversalt extends persistence
  23. {
  24. /**
  25. * generated salt
  26. *
  27. * @access private
  28. * @static
  29. * @var string
  30. */
  31. private static $_salt = '';
  32. /**
  33. * generate a large random hexadecimal salt
  34. *
  35. * @access public
  36. * @static
  37. * @return string
  38. */
  39. public static function generate()
  40. {
  41. $randomSalt = '';
  42. if (function_exists('mcrypt_create_iv'))
  43. {
  44. $randomSalt = bin2hex(mcrypt_create_iv(256, MCRYPT_DEV_URANDOM));
  45. }
  46. else // fallback to mt_rand()
  47. {
  48. for($i = 0; $i < 256; ++$i) {
  49. $randomSalt .= base_convert(mt_rand(), 10, 16);
  50. }
  51. }
  52. return $randomSalt;
  53. }
  54. /**
  55. * get server salt
  56. *
  57. * @access public
  58. * @static
  59. * @throws Exception
  60. * @return string
  61. */
  62. public static function get()
  63. {
  64. if (strlen(self::$_salt)) return self::$_salt;
  65. $file = 'salt.php';
  66. if (self::_exists($file)) {
  67. $items = explode('|', @file_get_contents(self::getPath($file)));
  68. if (!is_array($items) || count($items) != 3) {
  69. throw new Exception('unable to read file ' . self::getPath($file), 20);
  70. }
  71. self::$_salt = $items[1];
  72. } else {
  73. self::$_salt = self::generate();
  74. self::_store(
  75. $file,
  76. '<?php /* |'. self::$_salt . '| */ ?>'
  77. );
  78. }
  79. return self::$_salt;
  80. }
  81. /**
  82. * set the path
  83. *
  84. * @access public
  85. * @static
  86. * @param string $path
  87. * @return void
  88. */
  89. public static function setPath($path)
  90. {
  91. self::$_salt = '';
  92. parent::setPath($path);
  93. }
  94. }