Completed
Push — master ( 8674f8...456c00 )
by Tony Karavasilev (Тони
08:49
created

AbstractKeyedHashFunction::hashFile()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 32
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 19
c 1
b 0
f 0
dl 0
loc 32
ccs 18
cts 18
cp 1
rs 9.0111
cc 6
nc 6
nop 1
crap 6
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 66
        if (!is_string($filename)) {
149 22
            throw new \InvalidArgumentException('The file path must be of type string.');
150
        }
151
152 44
        $this->validateFileNamePath($filename);
153
154 22
        $useFileSalting = $this->isFileSaltingForcingNativeHashing();
155
156 22
        if ($this->useNative || $useFileSalting) {
157 22
            $oldSalt = $this->salt;
158 22
            $oldMode = $this->saltingMode;
159
160 22
            $this->salt = ($useFileSalting) ? $this->salt : '';
161 22
            $this->saltingMode = ($useFileSalting) ? $this->saltingMode : self::SALTING_MODE_NONE;
162
163 22
            $digest = $this->hashData(file_get_contents($filename));
164
165 22
            $this->setSalt($oldSalt)->setSaltingMode($oldMode);
166
        } else {
167 22
            $digest = hash_hmac_file(
168 22
                static::ALGORITHM_NAME,
169
                $filename,
170 22
                $this->key,
171 22
                ($this->digestFormat === self::DIGEST_OUTPUT_RAW)
172
            );
173
174 22
            $digest = $this->changeOutputFormat($digest);
175
        }
176
177 22
        return $digest;
178
    }
179
180
    /**
181
     * Get debug information for the class instance.
182
     *
183
     * @return array Debug information.
184
     */
185 22
    public function __debugInfo()
186
    {
187
        return [
188 22
            'standard' => static::ALGORITHM_NAME,
189 22
            'type' => 'keyed digestion or HMAC',
190 22
            'key' => $this->key,
191 22
            'salt' => $this->salt,
192 22
            'mode' => $this->saltingMode,
193
        ];
194
    }
195
}
196