Token.php
1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
namespace NinjaForms\Blocks\Authentication;
/**
* Creates an encoded public/private key hash and validates it.
*/
class Token {
/** @var string */
protected $privateKey;
/**
* @param string $privateKey
*/
public function __construct( $privateKey ) {
$this->privateKey = $privateKey;
}
/**
* @param string $publicKey
*
* @return string
*/
public function create( $publicKey ) {
return base64_encode( $this->hash( $publicKey ) . ':' . $publicKey );
}
/**
* @param string $token
*
* @return bool
*/
public function validate( $token ) {
// If the token is malformed, then list() may return an undefined index error.
// Pad the exploded array to add missing indexes, see https://www.php.net/manual/en/function.list.php#113189.
list( $hash, $publicKey ) = array_pad( explode( ':', base64_decode( $token ) ), 2, false );
return hash_equals( $hash, $this->hash( $publicKey ) );
}
/**
* @param string $publicKey
*
* @return string
*/
protected function hash( $publicKey ) {
return hash( 'sha256', $this->privateKey.$publicKey );
}
}