G
G
Galdar Turin2020-09-04 10:08:43
PHP
Galdar Turin, 2020-09-04 10:08:43

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;

I understand it's the key. But what is the key to write then? I read about JWT but I can’t understand

DOP:
As I understand it, the key is indicated in the footer
secret
5f51eb66b58a9150260974.png

And correctly, I understand that the JWT token that I receive from him needs to take the tail and translate it. Only here is how and from what has not yet figured out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2020-09-04
@Galdar

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

The third part is the signature. If you take the first two parts and get a sha265 hash using your key, it should match the first part. This will confirm that no one has changed the first two parts.
At least read the wiki , really :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question