<?php
function base64UrlEncode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
function base64UrlDecode($data) {
$data .= str_repeat('=', (4 - strlen($data) % 4) % 4);
return base64_decode(strtr($data, '-_', '+/'));
}
function jwtEncode($header, $payload, $secret) {
// Encode Header
$headerEncoded = base64UrlEncode(json_encode($header));
// Encode Payload
$payloadEncoded = base64UrlEncode(json_encode($payload));
// Create Signature
$signature = hash_hmac('sha256', $headerEncoded . "." . $payloadEncoded, $secret, true);
$signatureEncoded = base64UrlEncode($signature);
// Create JWT
return $headerEncoded . "." . $payloadEncoded . "." . $signatureEncoded;
}
function jwtDecode($jwt, $secret) {
// Split the JWT into its parts
list($headerEncoded, $payloadEncoded, $signatureEncoded) = explode('.', $jwt);
// Decode Header and Payload
$header = json_decode(base64UrlDecode($headerEncoded), true);
$payload = json_decode(base64UrlDecode($payloadEncoded), true);
// Verify Signature
$signature = base64UrlDecode($signatureEncoded);
$expectedSignature = hash_hmac('sha256', $headerEncoded . "." . $payloadEncoded, $secret, true);
if ($signature !== $expectedSignature) {
throw new Exception('Invalid signature');
}
// Check expiration
if (isset($payload['exp']) && $payload['exp'] < time()) {
throw new Exception('Token has expired');
}
return $payload;
}
// Example usage
$header = ['alg' => 'HS256', 'typ' => 'JWT'];
$payload = [
'iss' => 'http://yourdomain.com',
'aud' => 'http://yourdomain.com',
'iat' => time(),
'exp' => time() + 3600, // 1 hour expiration
'data' => [
'userId' => 123,
'username' => 'exampleUser '
]
];
$secret = 'your_secret_key';
// Encode the JWT
$jwt = jwtEncode($header, $payload, $secret);
echo "JWT: " . $jwt . "\n";
// Decode the JWT
try {
$decodedPayload = jwtDecode($jwt, $secret);
echo "User ID: " . $decodedPayload['data']['userId'] . "\n";
echo "Username: " . $decodedPayload['data']['username'] . "\n";
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
?>