Skip to content

Instantly share code, notes, and snippets.

@DarkGhostHunter
Last active November 11, 2022 05:26
Show Gist options
  • Save DarkGhostHunter/fb559d5f40dc40d37d310fd36be67f75 to your computer and use it in GitHub Desktop.
Save DarkGhostHunter/fb559d5f40dc40d37d310fd36be67f75 to your computer and use it in GitHub Desktop.
<?php
class SecureJSON
{
public $array;
public $key;
public function __construct(array $array)
{
$this->array = $array;
}
public function jsonSerialize()
{
$original = $this->array;
ksort($data);
$original['signature'] = hash_hmac('sha256', json_encode($data), $this->key);
return $original;
}
public static function fromJson(string $data, string $key)
{
$data = json_decode($data, true);
$signature = $data['signature'];
unset($data['signature']);
ksort($data);
if (hash_equals(hash_hmac('sha256', json_encode($data), $key)), $signature) {
return new static($data);
}
throw new \Exception('Invalid signature');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment