KwOrig::checkHash()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace kalanis\kw_auth_sources\Hashes;
4
5
6
use kalanis\kw_auth_sources\AuthSourcesException;
7
use kalanis\kw_auth_sources\Interfaces\IKAusTranslations;
8
use kalanis\kw_auth_sources\Interfaces\IHashes;
9
use kalanis\kw_auth_sources\Traits\TLang;
10
11
12
/**
13
 * Class KwOrig
14
 * @package kalanis\kw_auth_sources\Hashes
15
 * Older kwcms style of password hashing
16
 */
17
class KwOrig implements IHashes
18
{
19
    use TLang;
20
21
    protected string $salt = '';
22
23 5
    public function __construct(string $salt, ?IKAusTranslations $lang = null)
24
    {
25 5
        $this->setAusLang($lang);
26 5
        $this->salt = $salt;
27 5
    }
28
29 4
    public function checkHash(string $pass, string $hash): bool
30
    {
31 4
        return $hash == $this->hashPassword($pass);
32
    }
33
34 4
    public function createHash(string $pass, ?string $method = null): string
35
    {
36 4
        return $this->hashPassword($pass);
37
    }
38
39
    /**
40
     * @param string $input
41
     * @throws AuthSourcesException
42
     * @return string
43
     */
44 4
    protected function hashPassword(string $input): string
45
    {
46 4
        return base64_encode(bin2hex($this->makeHash($this->passSalt($input))));
47
    }
48
49 4
    private function passSalt(string $input): string
50
    {
51 4
        $ln = strlen($input);
52
        # pass is too long and salt too short
53 4
        $salt = (strlen($this->salt) < ($ln*5))
54 2
            ? str_repeat($this->salt, 5)
55 4
            : $this->salt ;
56 4
        return substr($salt, $ln, $ln)
57 4
            . substr($input,0, intval($ln/2))
58 4
            . substr($salt,$ln*2, $ln)
59 4
            . substr($input, intval($ln/2))
60 4
            . substr($salt,$ln*3, $ln);
61
    }
62
63
    /**
64
     * @param string $word
65
     * @throws AuthSourcesException
66
     * @return string
67
     */
68 4
    private function makeHash(string $word): string
69
    {
70 4
        if (function_exists('hash')) {
71 4
            return strval(hash('sha256', $word));
72
        }
73
        // @codeCoverageIgnoreStart
74
        throw new AuthSourcesException($this->getAusLang()->kauHashFunctionNotFound());
75
        // @codeCoverageIgnoreEnd
76
    }
77
}
78