Answer the question
In order to leave comments, you need to log in
How to decrypt JWT token?
Here is an example on the site
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Trying to decode it and fail.
$jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
$key = "";
$decoded = JWT::decode($jwt, $key, array('HS256'));
$answer = $decoded;
Answer the question
In order to leave comments, you need to log in
The token consists of three parts separated by a dot. Each part is encoded with slightly modified base64.
The first two are decoded without a key at all. At the end is a signature encoded with a key. In your example, this is
your-256-bit-secret
(try to print another key there on the right, where the blue one is, and see how the token changes).
<?php
$key = 'your-256-bit-secret'; // ваш ключ
$jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
$jwtArr = array_combine(['header', 'payload', 'signature'], explode('.', $jwtToken));
var_export($jwtArr); /* -> разделяем по точкам
array (
'header' => 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
'payload' => 'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ',
'signature' => 'SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c',
) */
echo PHP_EOL . base64_decode($jwtArr['header']) . PHP_EOL; // декодированный заголовок
// -> {"alg":"HS256","typ":"JWT"}
echo base64_decode($jwtArr['payload']) . PHP_EOL; // декодированная нагрузка
// -> {"sub":"1234567890","name":"John Doe","iat":1516239022}
$calculatedHash = hash_hmac( // сами считаем хеш
'sha256',
$jwtArr['header'] . '.' . $jwtArr['payload'],
$key,
true);
echo base64_encode($calculatedHash) . PHP_EOL;
// -> SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV/adQssw5c=
echo $jwtArr['signature'] . PHP_EOL;
// -> SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
// Похоже? Там слегка модифицированный base64
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question