serversalt.php 2.4 KB

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