Last active
November 11, 2022 05:26
-
-
Save DarkGhostHunter/fb559d5f40dc40d37d310fd36be67f75 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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