idObfuscation.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. define('ID_OBFUSCATION_SALT_FILE', __DIR__.'/idObfuscation_salt.php');
  3. /**
  4. * @return string|int
  5. */
  6. function getObfuscationSalt()
  7. {
  8. if (!file_exists(ID_OBFUSCATION_SALT_FILE)) {
  9. $bytes = openssl_random_pseudo_bytes(4);
  10. $saltData = "<?php\n\n\$OBFUSCATION_SALT = 0x".bin2hex($bytes).";\n";
  11. file_put_contents(ID_OBFUSCATION_SALT_FILE, $saltData);
  12. }
  13. if (
  14. file_exists(ID_OBFUSCATION_SALT_FILE)
  15. && is_readable(ID_OBFUSCATION_SALT_FILE)
  16. ) {
  17. require ID_OBFUSCATION_SALT_FILE;
  18. }
  19. return isset($OBFUSCATION_SALT) ? $OBFUSCATION_SALT : 0;
  20. }
  21. /**
  22. * This is a simple reversible hash function I made for encoding and decoding test IDs.
  23. * It is not cryptographically secure, don't use it to hash passwords or something!
  24. *
  25. * @param int|string $id
  26. * @param bool $dec
  27. *
  28. * @return int|string
  29. */
  30. function obfdeobf($id, $dec)
  31. {
  32. $salt = getObfuscationSalt() & 0xFFFFFFFF;
  33. $id &= 0xFFFFFFFF;
  34. if ($dec) {
  35. $id ^= $salt;
  36. $id = (($id & 0xAAAAAAAA) >> 1) | ($id & 0x55555555) << 1;
  37. $id = (($id & 0x0000FFFF) << 16) | (($id & 0xFFFF0000) >> 16);
  38. return $id;
  39. }
  40. $id = (($id & 0x0000FFFF) << 16) | (($id & 0xFFFF0000) >> 16);
  41. $id = (($id & 0xAAAAAAAA) >> 1) | ($id & 0x55555555) << 1;
  42. return $id ^ $salt;
  43. }
  44. /**
  45. * @param int $id
  46. *
  47. * @return string
  48. */
  49. function obfuscateId($id)
  50. {
  51. return str_pad(base_convert(obfdeobf($id + 1, false), 10, 36), 7, 0, STR_PAD_LEFT);
  52. }
  53. /**
  54. * @param string $id
  55. *
  56. * @return int
  57. */
  58. function deobfuscateId($id)
  59. {
  60. return obfdeobf(base_convert($id, 36, 10), true) - 1;
  61. }