Completed
Push — master ( e4d297...14927f )
by Tony Karavasilev (Тони
16:15
created

SecureVerificationTrait::verifyHash()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
1
<?php
2
3
/**
4
 * Trait implementation of the password and data verification process for digestion algorithms.
5
 */
6
7
namespace CryptoManana\Core\Traits\MessageDigestion;
8
9
use \CryptoManana\Core\Interfaces\MessageDigestion\SecureVerificationInterface as VerificationSpecification;
10
use \CryptoManana\Core\Abstractions\MessageDigestion\AbstractHashAlgorithm as AnyDerivedHashAlgorithm;
11
12
/**
13
 * Trait SecureVerificationTrait - Reusable implementation of `SecureVerificationInterface`.
14
 *
15
 * @see \CryptoManana\Core\Interfaces\MessageDigestion\SecureVerificationInterface The abstract specification.
16
 *
17
 * @package CryptoManana\Core\Traits\MessageDigestion
18
 *
19
 * @mixin VerificationSpecification
20
 * @mixin AnyDerivedHashAlgorithm
21
 */
22
trait SecureVerificationTrait
23
{
24
    /**
25
     * Calculates a hash value for the given data.
26
     *
27
     * @param string $data The input string.
28
     *
29
     * @return string The digest.
30
     * @throws \Exception Validation errors.
31
     */
32
    abstract public function hashData($data);
33
34
    /**
35
     * Securely compares and verifies if a digestion value is for the given input data.
36
     *
37
     * @param string $data The input string.
38
     * @param string $digest The digest string.
39
     *
40
     * @return bool The result of the secure comparison.
41
     * @throws \Exception Validation errors.
42
     *
43
     * @internal Do not forget to set the correct digestion settings for the current object before calling this method.
44
     */
45 66
    public function verifyHash($data, $digest)
46
    {
47 66
        if (!is_string($data)) {
48 22
            throw new \InvalidArgumentException('The data for hashing must be a string or a binary string.');
49 44
        } elseif (!is_string($digest)) {
1 ignored issue
show
introduced by
The condition is_string($digest) is always true.
Loading history...
50 22
            throw new \InvalidArgumentException('The digest must be a string or a binary string.');
51
        }
52
53 22
        $hash = $this->hashData($data);
54
55 22
        return hash_equals($hash, $digest);
56
    }
57
}
58