Created
March 14, 2017 21:37
-
-
Save paragonie-scott/9b48c4e83ba658758e57a50e23f21bf9 to your computer and use it in GitHub Desktop.
PHP 7.2 Replacement for JWT
This file contains hidden or 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 | |
declare(strict_types=1); | |
use ParagonIE\ConstantTime\Base64UrlSafe; | |
class JWTKiller | |
{ | |
public static function sign(string $message, Key $key): string | |
{ | |
$mac = sodium_crypto_auth($message, $key->getRaw()); | |
return Base64UrlSafe::encode($mac) . $message; | |
} | |
public static function verify(string $signedMessage, Key $key): string | |
{ | |
if (mb_strlen($signedMessage, '8bit') < 44) { | |
throw new Exception('Message too short'); | |
} | |
$mac = Base64UrlSafe::decode(mb_substr($signedMessage, 0, 44, '8bit')); | |
$message = mb_substr($signedMessage, 44, null, '8bit'); | |
if (!sodium_crypto_auth_verify($mac, $message, $key->getRaw()) { | |
throw new Error('Invalid message authentication code'); | |
} | |
return $message; | |
} | |
} |
This file contains hidden or 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 | |
declare(strict_types=1); | |
class Key | |
{ | |
protected $raw; | |
public function __construct(string $raw) | |
{ | |
$this->raw = $raw; | |
} | |
public function getRaw(): string | |
{ | |
return $this->raw; | |
} | |
public static function generate(): self | |
{ | |
return new Key(random_bytes(32)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment