ServerSalt.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 1.2.1
  11. */
  12. namespace PrivateBin\Persistence;
  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 AbstractPersistence
  25. {
  26. /**
  27. * file where salt is saved to
  28. *
  29. * @access private
  30. * @static
  31. * @var string
  32. */
  33. private static $_file = 'salt.php';
  34. /**
  35. * generated salt
  36. *
  37. * @access private
  38. * @static
  39. * @var string
  40. */
  41. private static $_salt = '';
  42. /**
  43. * generate a large random hexadecimal salt
  44. *
  45. * @access public
  46. * @static
  47. * @return string
  48. */
  49. public static function generate()
  50. {
  51. $randomSalt = bin2hex(random_bytes(256));
  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)) {
  65. return self::$_salt;
  66. }
  67. if (self::_exists(self::$_file)) {
  68. if (is_readable(self::getPath(self::$_file))) {
  69. $items = explode('|', file_get_contents(self::getPath(self::$_file)));
  70. }
  71. if (!isset($items) || !is_array($items) || count($items) != 3) {
  72. throw new Exception('unable to read file ' . self::getPath(self::$_file), 20);
  73. }
  74. self::$_salt = $items[1];
  75. } else {
  76. self::$_salt = self::generate();
  77. self::_store(
  78. self::$_file,
  79. '<?php # |' . self::$_salt . '|'
  80. );
  81. }
  82. return self::$_salt;
  83. }
  84. /**
  85. * set the path
  86. *
  87. * @access public
  88. * @static
  89. * @param string $path
  90. */
  91. public static function setPath($path)
  92. {
  93. self::$_salt = '';
  94. parent::setPath($path);
  95. }
  96. }