Skip to content

Instantly share code, notes, and snippets.

@astrolox
Created June 4, 2021 14:09
Show Gist options
  • Save astrolox/d2ede784d18e61d1588e975c5ce136b4 to your computer and use it in GitHub Desktop.
Save astrolox/d2ede784d18e61d1588e975c5ce136b4 to your computer and use it in GitHub Desktop.
PHP 5.1 RS256 JWT
<?php
// Written for PHP 5.1 without openssl
// phpseclib version 1.0.19 (PHP 4 compatible)
// http://sourceforge.net/projects/phpseclib/files/phpseclib1.0.19.zip/download
// https://github.com/phpseclib/phpseclib
include 'Crypt/Hash.php';
include 'Crypt/RSA.php';
$rsa = new Crypt_RSA();
extract($rsa->createKey());
echo $publickey ."\n";
echo $privatekey ."\n";
echo "--------------------------------------------------\n";
// With thanks to Rob Waller
// https://dev.to/robdwaller/how-to-create-a-json-web-token-using-php-3gml
// Create token header as a JSON string
$header = json_encode(array('typ' => 'JWT', 'alg' => 'RS256'));
// Create token payload as a JSON string
$payload = json_encode(array('user_id' => 123));
// Encode Header to Base64Url String
$base64UrlHeader = str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($header));
// Encode Payload to Base64Url String
$base64UrlPayload = str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($payload));
// Create Signature Hash ... using RS256 (not HS256) ...
$rsa->loadKey($privatekey);
$rsa->setHash('sha256');
$rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
$signature = $rsa->sign($base64UrlHeader . "." . $base64UrlPayload);
// Encode Signature to Base64Url String
$base64UrlSignature = str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($signature));
// Create JWT
$jwt = $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
echo $jwt ."\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment