Skip to content

Instantly share code, notes, and snippets.

@paragonie-scott
Created March 14, 2017 21:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save paragonie-scott/9b48c4e83ba658758e57a50e23f21bf9 to your computer and use it in GitHub Desktop.
Save paragonie-scott/9b48c4e83ba658758e57a50e23f21bf9 to your computer and use it in GitHub Desktop.
PHP 7.2 Replacement for JWT
<?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;
}
}
<?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