HashedSearchable.php 1.41 KB
Newer Older
Jacob Priddy's avatar
Jacob Priddy committed
1
2
3
4
5
<?php


namespace Source\Entities;

6
class HashedSearchable
Jacob Priddy's avatar
Jacob Priddy committed
7
8
9
10
11
12
13
{
    /**
     * @var string
     */
    protected string $hash;

    /**
14
     * Construct from existing hash
Jacob Priddy's avatar
Jacob Priddy committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
     *
     * @param string $hash
     */
    public function __construct(string $hash)
    {
        $this->hash = $hash;
    }

    /**
     * @param string      $salt
     * @param string|null $plaintext
     * @return static|null
     */
    public static function hash(string $salt, ?string $plaintext): ?self
    {
        if (!$plaintext) {
            return null;
        }

        // Two rounds of sha512 each salted
        // As of PHP 7 the salt parameter to password_hash has been depreciated.
36
37
        // As we need to be able to search for these values they either all need to have the same salt
        // or no salt (I'd prefer a salt). This way the value can be hashed and
Jacob Priddy's avatar
Jacob Priddy committed
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
        // then easily searched for in the database without having to check against every user and rehash every
        // time with the new salt. As such it is not as easy to use BCRYPT :(
        // So I'll just shred it twice using sha512 with with (probably) the application key.
        return new static(
            hash(
                'sha512',
                hash('sha512', $plaintext . $salt)
                . $salt
            )
        );
    }

    /**
     * @return string
     */
    public function getHash(): string
    {
        return $this->hash;
    }
}