Passed
Branch master (de8919)
by Tony Karavasilev (Тони
02:41
created

SecretKeyTrait::setSecretKey()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 18
ccs 9
cts 9
cp 1
rs 10
cc 4
nc 4
nop 1
crap 4
1
<?php
2
3
/**
4
 * Trait implementation of the secret key capabilities for symmetric encryption algorithms.
5
 */
6
7
namespace CryptoManana\Core\Traits\MessageEncryption;
8
9
use \CryptoManana\Core\Interfaces\MessageEncryption\SecretKeyInterface as SecretKeySpecification;
10
11
/**
12
 * Trait SecretKeyTrait - Reusable implementation of `SecretKeyInterface`.
13
 *
14
 * @see \CryptoManana\Core\Interfaces\MessageDigestion\SecretKeyInterface The abstract specification.
15
 *
16
 * @package CryptoManana\Core\Traits\MessageEncryption
17
 *
18
 * @property string $key The encryption/decryption secret key property storage.
19
 *
20
 * @mixin SecretKeySpecification
21
 */
22
trait SecretKeyTrait
23
{
24
    /**
25
     * Setter for the secret key string property.
26
     *
27
     * @param string $key The encryption key string.
28
     *
29
     * @return $this The encryption algorithm object.
30
     * @throws \Exception Validation errors.
31
     */
32 48
    public function setSecretKey($key)
33
    {
34 48
        if (!is_string($key)) {
35 12
            throw new \InvalidArgumentException('The secret key must be a string or a binary string.');
36
        }
37
38
        /**
39
         * {@internal The encryption standard is 8-bit wise (don not use StringBuilder) and utilizes performance. }}
40
         */
41 36
        if (strlen($key) > static::KEY_SIZE) {
42 12
            $key = hash_hkdf('sha256', $key, static::KEY_SIZE, 'CryptoMañana', '');
43 36
        } elseif (strlen($key) < static::KEY_SIZE) {
44 12
            $key = str_pad($key, static::KEY_SIZE, "\x0", STR_PAD_RIGHT);
45
        }
46
47 36
        $this->key = $key;
48
49 36
        return $this;
50
    }
51
52
    /**
53
     * Getter for the secret key string property.
54
     *
55
     * @return string The encryption key string.
56
     */
57 36
    public function getSecretKey()
58
    {
59 36
        return $this->key;
60
    }
61
}
62