RobDWaller / ReallySimpleJWT
1
<?php
2

3
namespace ReallySimpleJWT\Encoders;
4

5
use ReallySimpleJWT\Interfaces\Encode;
6
use ReallySimpleJWT\Helper\JsonEncoder;
7
use ReallySimpleJWT\Helper\Base64;
8

9
/**
10
 * HS256 / sha256 implementation of the Encode interface.
11
 *
12
 * Core ReallySimpleJWT token encoder class for encoding JWT parts
13
 * and signatures.
14
 */
15
class EncodeHS256 implements Encode
16
{
17
    use JsonEncoder;
18
    use Base64;
19

20
    /**
21
     * The Algorithm which was used to hash the token signature. This is what
22
     * is displayed as the alg claim in the token header. Note this may be
23
     * slightly different from the actual algorithm used to hash the
24
     * signature string.
25
     */
26
    private const ALGORITHM = 'HS256';
27

28
    /**
29
     * This is the actual algorithm used to hash the token's signature string.
30
     */
31
    private const HASH_ALGORITHM = 'sha256';
32

33
    /**
34
     * Get the algorithm used to encode the signature. Note this is for show,
35
     * it is what is displayed in the JWT header as the alg claim.
36
     */
37 16
    public function getAlgorithm(): string
38
    {
39 16
        return self::ALGORITHM;
40
    }
41

42
    /**
43
     * Get the hash algorithm string to be used when encoding the signature,
44
     * this is the actual hash type used to encode the signature.
45
     */
46 16
    private function getHashAlgorithm(): string
47
    {
48 16
        return self::HASH_ALGORITHM;
49
    }
50

51
    /**
52
     * Encode a JSON string to a Base64Url string.
53
     */
54 16
    private function urlEncode(string $toEncode): string
55
    {
56 16
        return $this->toBase64Url(base64_encode($toEncode));
57
    }
58

59
    /**
60
     * Encode a json string in Base64 Url format.
61
     *
62
     * @param mixed[] $toEncode
63
     */
64 16
    public function encode(array $toEncode): string
65
    {
66 16
        return $this->urlEncode($this->jsonEncode($toEncode));
67
    }
68

69
    /**
70
     * Generate the JWT signature. The header and payload are encoded,
71
     * concatenated with a dot, hashed via sha256 with a secret, and then
72
     * encoded and returned.
73
     *
74
     * @param mixed[] $header
75
     * @param mixed[] $payload
76
     */
77 16
    public function signature(array $header, array $payload, string $secret): string
78
    {
79 16
        return $this->urlEncode(
80 16
            $this->hash(
81 16
                $this->getHashAlgorithm(),
82 16
                $this->encode($header) . "." . $this->encode($payload),
83
                $secret
84
            )
85
        );
86
    }
87

88
    /**
89
     * Hash the JWT signature string using sha256.
90
     */
91 16
    private function hash(string $algorithm, string $toHash, string $secret): string
92
    {
93 16
        return hash_hmac($algorithm, $toHash, $secret, true);
94
    }
95
}

Read our documentation on viewing source code .

Loading