nextpage.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. class nextpage{
  3. public function __construct($scraper){
  4. $this->scraper = $scraper;
  5. }
  6. public function store($payload, $page){
  7. $page = $page[0];
  8. $password = random_bytes(256); // 2048 bit
  9. $salt = random_bytes(16);
  10. $key = hash_pbkdf2("sha512", $password, $salt, 20000, 32, true);
  11. $iv =
  12. random_bytes(
  13. openssl_cipher_iv_length("aes-256-gcm")
  14. );
  15. $tag = "";
  16. $out = openssl_encrypt($payload, "aes-256-gcm", $key, OPENSSL_RAW_DATA, $iv, $tag, "", 16);
  17. $key = apcu_inc("key", 1);
  18. apcu_store(
  19. $page . "." .
  20. $this->scraper .
  21. (string)$key,
  22. gzdeflate($salt.$iv.$out.$tag),
  23. 900 // cache information for 15 minutes blaze it
  24. );
  25. return
  26. $this->scraper . $key . "." .
  27. rtrim(strtr(base64_encode($password), '+/', '-_'), '=');
  28. }
  29. public function get($npt, $page){
  30. $page = $page[0];
  31. $explode = explode(".", $npt, 2);
  32. if(count($explode) !== 2){
  33. throw new Exception("Malformed nextPageToken!");
  34. }
  35. $apcu = $page . "." . $explode[0];
  36. $key = $explode[1];
  37. $payload = apcu_fetch($apcu);
  38. if($payload === false){
  39. throw new Exception("The nextPageToken is invalid or has expired!");
  40. }
  41. $key =
  42. base64_decode(
  43. str_pad(
  44. strtr($key, '-_', '+/'),
  45. strlen($key) % 4,
  46. '=',
  47. STR_PAD_RIGHT
  48. )
  49. );
  50. $payload = gzinflate($payload);
  51. $key =
  52. hash_pbkdf2(
  53. "sha512",
  54. $key,
  55. substr($payload, 0, 16), // salt
  56. 20000,
  57. 32,
  58. true
  59. );
  60. $ivlen = openssl_cipher_iv_length("aes-256-gcm");
  61. $payload =
  62. openssl_decrypt(
  63. substr(
  64. $payload,
  65. 16 + $ivlen,
  66. -16
  67. ),
  68. "aes-256-gcm",
  69. $key,
  70. OPENSSL_RAW_DATA,
  71. substr($payload, 16, $ivlen),
  72. substr($payload, -16)
  73. );
  74. if($payload === false){
  75. throw new Exception("The nextPageToken is invalid or has expired!");
  76. }
  77. // remove the key after using
  78. apcu_delete($apcu);
  79. return $payload;
  80. }
  81. }