Completed
Push — master ( da3f44...ad9152 )
by Tony Karavasilev (Тони
08:26
created

isFileSaltingForcingNativeHashing()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 11
ccs 5
cts 5
cp 1
rs 10
cc 4
nc 5
nop 0
crap 4
1
<?php
2
3
/**
4
 * Abstraction for keyed hash objects like HMAC functions (keyed-hash message authentication code hash).
5
 */
6
7
namespace CryptoManana\Core\Abstractions\MessageDigestion;
8
9
use \CryptoManana\Core\Abstractions\MessageDigestion\AbstractHashAlgorithm as HashAlgorithm;
10
use \CryptoManana\Core\Interfaces\MessageDigestion\DigestionKeyInterface as KeyedHashing;
11
use \CryptoManana\Core\Interfaces\MessageDigestion\ObjectHashingInterface as ObjectHashing;
12
use \CryptoManana\Core\Interfaces\MessageDigestion\FileHashingInterface as FileHashing;
13
use \CryptoManana\Core\Traits\MessageDigestion\DigestionKeyTrait as DigestionKey;
14
use \CryptoManana\Core\Traits\MessageDigestion\ObjectHashingTrait as HashObjects;
15
use \CryptoManana\Core\StringBuilder as StringBuilder;
16
17
/**
18
 * Class AbstractKeyedHashFunction - Abstraction for keyed hash classes.
19
 *
20
 * @package CryptoManana\Core\Abstractions\MessageDigestion
21
 *
22
 * @mixin DigestionKey
23
 * @mixin HashObjects
24
 */
25
abstract class AbstractKeyedHashFunction extends HashAlgorithm implements KeyedHashing, ObjectHashing, FileHashing
26
{
27
    /**
28
     * Data salting capabilities.
29
     *
30
     * {@internal Reusable implementation of `DigestionKeyInterface`. }}
31
     */
32
    use DigestionKey;
33
34
    /**
35
     * Object hashing capabilities.
36
     *
37
     * {@internal Reusable implementation of `ObjectHashingInterface`. }}
38
     */
39
    use HashObjects;
40
41
    /**
42
     * The internal name of the algorithm.
43
     */
44
    const ALGORITHM_NAME = 'none';
45
46
    /**
47
     * Flag to force native code polyfill realizations, if available.
48
     *
49
     * @var bool Flag to force native realizations.
50
     */
51
    protected $useNative = false;
52
53
    /**
54
     * The key string property storage.
55
     *
56
     * @var string The digestion key string value.
57
     */
58
    protected $key = '';
59
60
    /**
61
     * Internal method for location and filename validation.
62
     *
63
     * @param string $filename The filename and location.
64
     *
65
     * @throws \Exception Validation errors.
66
     */
67 44
    protected function validateFileNamePath($filename)
68
    {
69 44
        $filename = StringBuilder::stringReplace("\0", '', $filename); // (ASCII 0 (0x00))
70 44
        $filename = realpath($filename); // Path traversal escape and absolute path fetching
71
72
        // Clear path cache
73 44
        if (!empty($filename)) {
74 22
            clearstatcache(true, $filename);
75
        }
76
77
        // Check if path is valid and the file is readable
78 44
        if ($filename === false || !file_exists($filename) || !is_readable($filename) || !is_file($filename)) {
79 22
            throw new \RuntimeException('File is not found or can not be accessed.');
80
        }
81 22
    }
82
83
    /**
84
     * Internal method for checking if native file hashing should be used by force.
85
     *
86
     * @return bool Is native hashing needed for the current salting mode.
87
     */
88 22
    protected function isFileSaltingForcingNativeHashing()
89
    {
90
        return (
91
            (
92
                // If there is an non-empty salt string set and salting is enabled
93 22
                $this->salt !== '' &&
94 22
                $this->saltingMode !== self::SALTING_MODE_NONE
95
            ) || (
96
                // If there is an empty salt string set and the salting mode duplicates/manipulates the input
97 22
                $this->salt === '' &&
98 22
                in_array($this->saltingMode, [self::SALTING_MODE_INFIX_SALT, self::SALTING_MODE_PALINDROME_MIRRORING])
99
            )
100
        );
101
    }
102
103
    /**
104
     * Unkeyed hash algorithm constructor.
105
     */
106 396
    public function __construct()
107
    {
108 396
    }
109
110
    /**
111
     * Calculates a hash value for the given data.
112
     *
113
     * @param string $data The input string.
114
     *
115
     * @return string The digest.
116
     * @throws \Exception Validation errors.
117
     */
118 140
    public function hashData($data)
119
    {
120 140
        if (!is_string($data)) {
121 14
            throw new \InvalidArgumentException('The data for hashing must be a string or a binary string.');
122
        }
123
124 126
        $data = $this->addSaltString($data);
125
126 126
        $digest = hash_hmac(
127 126
            static::ALGORITHM_NAME,
128
            $data,
129 126
            $this->key,
130 126
            ($this->digestFormat === self::DIGEST_OUTPUT_RAW)
131
        );
132
133 126
        $digest = $this->changeOutputFormat($digest);
134
135 126
        return $digest;
136
    }
137
138
    /**
139
     * Calculates a hash value for the content of the given filename and location.
140
     *
141
     * @param string $filename The full path and name of the file for hashing.
142
     *
143
     * @return string The digest.
144
     * @throws \Exception Validation errors.
145
     */
146 66
    public function hashFile($filename)
147
    {
148
        // Validate input type
149 66
        if (!is_string($filename)) {
150 22
            throw new \InvalidArgumentException('The file path must be of type string.');
151
        }
152
153 44
        $this->validateFileNamePath($filename);
154
155 22
        $useFileSalting = $this->isFileSaltingForcingNativeHashing();
156
157 22
        if ($this->useNative || $useFileSalting) {
158
            /**
159
             * {@internal An optimization for native performance that spears string manipulations and function calls. }}
160
             */
161 22
            if (!$useFileSalting) {
162 22
                $oldSalt = $this->salt;
163 22
                $oldMode = $this->saltingMode;
164
165 22
                $this->salt = '';
166 22
                $this->saltingMode = self::SALTING_MODE_NONE;
167
            }
168
169 22
            $digest = $this->hashData(file_get_contents($filename));
170
171 22
            if (!$useFileSalting && isset($oldSalt, $oldMode)) {
172 22
                $this->salt = $oldSalt;
173 22
                $this->saltingMode = $oldMode;
174
            }
175
        } else {
176 22
            $digest = hash_hmac_file(
177 22
                static::ALGORITHM_NAME,
178
                $filename,
179 22
                $this->key,
180 22
                ($this->digestFormat === self::DIGEST_OUTPUT_RAW)
181
            );
182
183 22
            $digest = $this->changeOutputFormat($digest);
184
        }
185
186 22
        return $digest;
187
    }
188
189
    /**
190
     * Get debug information for the class instance.
191
     *
192
     * @return array Debug information.
193
     */
194 22
    public function __debugInfo()
195
    {
196
        return [
197 22
            'standard' => static::ALGORITHM_NAME,
198 22
            'type' => 'keyed digestion or HMAC',
199 22
            'key' => $this->key,
200 22
            'salt' => $this->salt,
201 22
            'mode' => $this->saltingMode,
202
        ];
203
    }
204
}
205