Passed
Pull Request — master (#11)
by Alexander
13:50
created

Crypt::withKdfAlgorithm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 10
c 1
b 0
f 0
ccs 4
cts 4
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Security;
6
7
use Yiisoft\Strings\StringHelper;
8
9
final class Crypt
10
{
11
    /**
12
     * @var array[] Look-up table of block sizes and key sizes for each supported OpenSSL cipher.
13
     *
14
     * In each element, the key is one of the ciphers supported by OpenSSL {@see openssl_get_cipher_methods()}.
15
     * The value is an array of two integers, the first is the cipher's block size in bytes and the second is
16
     * the key size in bytes.
17
     *
18
     * > Note: Yii's encryption protocol uses the same size for cipher key, HMAC signature key and key
19
     * derivation salt.
20
     */
21
    private const ALLOWED_CIPHERS = [
22
        'AES-128-CBC' => [16, 16],
23
        'AES-192-CBC' => [16, 24],
24
        'AES-256-CBC' => [16, 32],
25
    ];
26
27
    /**
28
     * @var string The cipher to use for encryption and decryption.
29
     */
30
    private string $cipher;
31
32
    /**
33
     * @var string Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
34
     * @see http://php.net/manual/en/function.hash-algos.php
35
     */
36
    private string $kdfAlgorithm = 'sha256';
37
38
    /**
39
     * @var string HKDF info value for derivation of message authentication key.
40
     */
41
    private string $authorizationKeyInfo = 'AuthorizationKey';
42
    /**
43
     * @var int Derivation iterations count.
44
     * Set as high as possible to hinder dictionary password attacks.
45
     */
46
    private int $derivationIterations = 100000;
47
48 48
    /**
49
     * @param string $cipher The cipher to use for encryption and decryption.
50 48
     */
51 1
    public function __construct(string $cipher = 'AES-128-CBC')
52
    {
53 47
        if (!extension_loaded('openssl')) {
54 1
            throw new \RuntimeException('Encryption requires the OpenSSL PHP extension');
55
        }
56
        if (!isset(self::ALLOWED_CIPHERS[$cipher][0], self::ALLOWED_CIPHERS[$cipher][1])) {
57 46
            throw new \RuntimeException($cipher . ' is not an allowed cipher');
58 46
        }
59
60 1
        $this->cipher = $cipher;
61
    }
62 1
63 1
    /**
64 1
     * @param string $algorithm Hash algorithm for key derivation. Recommend sha256, sha384 or sha512.
65
     * @return self
66
     */
67 1
    public function withKdfAlgorithm(string $algorithm): self
68
    {
69 1
        $new = clone $this;
70 1
        $new->kdfAlgorithm = $algorithm;
71 1
        return $new;
72
    }
73
74 44
    /**
75
     * @param string $info HKDF info value for derivation of message authentication key.
76 44
     * @return self
77 44
     */
78 44
    public function withAuthorizationKeyInfo(string $info): self
79
    {
80
        $new = clone $this;
81
        $new->authorizationKeyInfo = $info;
82
        return $new;
83
    }
84
85
    /**
86
     * @param int $iterations Derivation iterations count.
87
     * Set as high as possible to hinder dictionary password attacks.
88
     * @return self
89
     */
90
    public function withDerivationIterations(int $iterations): self
91
    {
92
        $new = clone $this;
93
        $new->derivationIterations = $iterations;
94
        return $new;
95
    }
96
97
    /**
98
     * Encrypts data using a password.
99 4
     *
100
     * Derives keys for encryption and authentication from the password using PBKDF2 and a random salt,
101 4
     * which is deliberately slow to protect against dictionary attacks. Use {@see encryptByKey()} to
102
     * encrypt fast using a cryptographic key rather than a password. Key derivation time is
103
     * determined by {@see $derivationIterations}}, which should be set as high as possible.
104
     *
105
     * The encrypted data includes a keyed message authentication code (MAC) so there is no need
106
     * to hash input or output data.
107
     *
108
     * > Note: Avoid encrypting with passwords wherever possible. Nothing can protect against
109
     * poor-quality or compromised passwords.
110
     *
111
     * @param string $data The data to encrypt.
112
     * @param string $password The password to use for encryption.
113
     * @return string The encrypted data as byte string.
114
     * @throws \RuntimeException On OpenSSL not loaded.
115
     * @throws \Exception On OpenSSL error.
116
     * @see decryptByPassword()
117
     * @see encryptByKey()
118
     */
119
    public function encryptByPassword(string $data, string $password): string
120
    {
121 4
        return $this->encrypt($data, true, $password, '');
122
    }
123 4
124
    /**
125
     * Encrypts data using a cryptographic key.
126
     *
127
     * Derives keys for encryption and authentication from the input key using HKDF and a random salt,
128
     * which is very fast relative to {@see encryptByPassword()}. The input key must be properly
129
     * random — use {@see random_bytes()} to generate keys.
130
     * The encrypted data includes a keyed message authentication code (MAC) so there is no need
131
     * to hash input or output data.
132
     *
133
     * @param string $data The data to encrypt.
134
     * @param string $inputKey The input to use for encryption and authentication.
135
     * @param string $info Context/application specific information, e.g. a user ID
136 21
     * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
137
     * @return string The encrypted data as byte string.
138 21
     * @throws \RuntimeException On OpenSSL not loaded.
139
     * @throws \Exception On OpenSSL error.
140
     * @see decryptByKey()
141
     * @see encryptByPassword()
142
     */
143
    public function encryptByKey(string $data, string $inputKey, string $info = ''): string
144
    {
145
        return $this->encrypt($data, false, $inputKey, $info);
146
    }
147
148
    /**
149
     * Verifies and decrypts data encrypted with {@see encryptByPassword()}.
150
     *
151
     * @param string $data The encrypted data to decrypt.
152
     * @param string $password The password to use for decryption.
153 22
     * @return string The decrypted data.
154
     * @throws \RuntimeException On OpenSSL not loaded.
155 22
     * @throws \Exception On OpenSSL errors.
156
     * @throws AuthenticationException On authentication failure.
157
     * @see encryptByPassword()
158
     */
159
    public function decryptByPassword(string $data, string $password): string
160
    {
161
        return $this->decrypt($data, true, $password, '');
162
    }
163
164
    /**
165
     * Verifies and decrypts data encrypted with {@see encryptByKey()}.
166
     *
167
     * @param string $data The encrypted data to decrypt.
168
     * @param string $inputKey The input to use for encryption and authentication.
169
     * @param string $info Context/application specific information, e.g. a user ID
170
     * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
171
     * @return string The decrypted data.
172 8
     * @throws \RuntimeException On OpenSSL not loaded.
173
     * @throws \Exception On OpenSSL errors.
174 8
     * @throws AuthenticationException On authentication failure.
175
     * @see encryptByKey()
176 8
     */
177 8
    public function decryptByKey(string $data, string $inputKey, string $info = ''): string
178 4
    {
179
        return $this->decrypt($data, false, $inputKey, $info);
180 4
    }
181
182
    /**
183 8
     * Encrypts data.
184
     *
185 8
     * @param string $data data to be encrypted
186 8
     * @param bool $passwordBased set true to use password-based key derivation
187 1
     * @param string $secret the encryption password or key
188
     * @param string $info context/application specific information, e.g. a user ID
189
     * See [RFC 5869 Section 3.2](https://tools.ietf.org/html/rfc5869#section-3.2) for more details.
190 7
     *
191 7
     * @return string the encrypted data as byte string
192
     * @throws \RuntimeException on OpenSSL not loaded
193
     * @throws \Exception on OpenSSL error
194
     * @see decrypt()
195
     */
196
    private function encrypt(string $data, bool $passwordBased, string $secret, string $info = ''): string
197
    {
198
        [$blockSize, $keySize] = self::ALLOWED_CIPHERS[$this->cipher];
199 7
200
        $keySalt = random_bytes($keySize);
201
        if ($passwordBased) {
202
            $key = hash_pbkdf2($this->kdfAlgorithm, $secret, $keySalt, $this->derivationIterations, $keySize, true);
203
        } else {
204
            $key = hash_hkdf($this->kdfAlgorithm, $secret, $keySize, $info, $keySalt);
205
        }
206
207
        $iv = random_bytes($blockSize);
208
209
        $encrypted = openssl_encrypt($data, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
210
        if ($encrypted === false) {
211
            throw new \RuntimeException('OpenSSL failure on encryption: ' . openssl_error_string());
212
        }
213
214
        $authKey = hash_hkdf($this->kdfAlgorithm, $key, $keySize, $this->authorizationKeyInfo);
215
        $signed = (new Mac())->sign($iv . $encrypted, $authKey);
0 ignored issues
show
Bug introduced by
Are you sure $encrypted of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

215
        $signed = (new Mac())->sign($iv . /** @scrutinizer ignore-type */ $encrypted, $authKey);
Loading history...
216 43
217
        /*
218 43
         * Output: [keySalt][MAC][IV][ciphertext]
219
         * - keySalt is KEY_SIZE bytes long
220 43
         * - MAC: message authentication code, length same as the output of MAC_HASH
221 43
         * - IV: initialization vector, length $blockSize
222 21
         */
223
        return $keySalt . $signed;
224 22
    }
225
226
    /**
227 43
     * Decrypts data.
228
     *
229
     * @param string $data encrypted data to be decrypted.
230 43
     * @param bool $passwordBased set true to use password-based key derivation
231 3
     * @param string $secret the decryption password or key
232 3
     * @param string $info context/application specific information, @see encrypt()
233
     *
234
     * @return string the decrypted data
235 40
     * @throws \RuntimeException on OpenSSL not loaded
236 40
     * @throws \Exception on OpenSSL errors
237
     * @throws AuthenticationException on authentication failure
238 40
     * @see encrypt()
239 40
     */
240 1
    private function decrypt(string $data, bool $passwordBased, string $secret, string $info): string
241
    {
242
        [$blockSize, $keySize] = self::ALLOWED_CIPHERS[$this->cipher];
243 39
244
        $keySalt = StringHelper::byteSubstring($data, 0, $keySize);
245
        if ($passwordBased) {
246
            $key = hash_pbkdf2($this->kdfAlgorithm, $secret, $keySalt, $this->derivationIterations, $keySize, true);
247
        } else {
248
            $key = hash_hkdf($this->kdfAlgorithm, $secret, $keySize, $info, $keySalt);
249
        }
250
251
        $authKey = hash_hkdf($this->kdfAlgorithm, $key, $keySize, $this->authorizationKeyInfo);
252
253
        try {
254
            $data = (new Mac())->getMessage(StringHelper::byteSubstring($data, $keySize), $authKey);
255
        } catch (DataIsTamperedException $e) {
256
            throw new AuthenticationException('Failed to decrypt data');
257
        }
258
259
        $iv = StringHelper::byteSubstring($data, 0, $blockSize);
260
        $encrypted = StringHelper::byteSubstring($data, $blockSize);
261
262
        $decrypted = openssl_decrypt($encrypted, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
263
        if ($decrypted === false) {
264
            throw new \RuntimeException('OpenSSL failure on decryption: ' . openssl_error_string());
265
        }
266
267
        return $decrypted;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $decrypted could return the type true which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
268
    }
269
}
270