validateCipherOrSignatureData()   A
last analyzed

Complexity

Conditions 6
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 13
c 2
b 0
f 0
dl 0
loc 19
ccs 15
cts 15
cp 1
rs 9.2222
cc 6
nc 5
nop 1
crap 6
1
<?php
2
3
/**
4
 * The asymmetric RSA algorithm abstraction specification.
5
 */
6
7
namespace CryptoManana\Core\Abstractions\MessageEncryption;
8
9
use CryptoManana\Core\Abstractions\MessageEncryption\AbstractAsymmetricEncryptionAlgorithm as AsymmetricAlgorithm;
10
use CryptoManana\Core\Interfaces\MessageEncryption\DataEncryptionInterface as AsymmetricDataEncryption;
11
use CryptoManana\Core\Interfaces\MessageEncryption\AsymmetricPaddingInterface as AsymmetricDataPadding;
12
use CryptoManana\Core\Interfaces\MessageEncryption\ObjectEncryptionInterface as ObjectEncryption;
13
use CryptoManana\Core\Interfaces\MessageEncryption\FileEncryptionInterface as FileEncryption;
14
use CryptoManana\Core\Interfaces\MessageEncryption\CipherDataFormatsInterface as CipherDataFormatting;
15
use CryptoManana\Core\Traits\MessageEncryption\AsymmetricPaddingTrait as RsaPaddingStandards;
16
use CryptoManana\Core\Traits\MessageEncryption\ObjectEncryptionTrait as EncryptObjects;
17
use CryptoManana\Core\Traits\MessageEncryption\FileEncryptionTrait as EncryptFiles;
18
use CryptoManana\Core\Traits\MessageEncryption\CipherDataFormatsTrait as CipherDataFormats;
19
20
/**
21
 * Class AbstractRsaEncryption - The RSA encryption algorithm abstraction representation.
22
 *
23
 * @package CryptoManana\Core\Abstractions\MessageEncryption
24
 *
25
 * @mixin RsaPaddingStandards
26
 * @mixin CipherDataFormats
27
 */
28
abstract class AbstractRsaEncryption extends AsymmetricAlgorithm implements
29
    AsymmetricDataEncryption,
30
    AsymmetricDataPadding,
31
    ObjectEncryption,
32
    FileEncryption,
33
    CipherDataFormatting
34
{
35
    /**
36
     * The RSA data padding basic standards.
37
     *
38
     * {@internal Reusable implementation of `AsymmetricPaddingInterface`. }}
39
     */
40
    use RsaPaddingStandards;
41
42
    /**
43
     * Object encryption and decryption capabilities.
44
     *
45
     * {@internal Reusable implementation of `ObjectEncryptionInterface`. }}
46
     */
47
    use EncryptObjects;
48
49
    /**
50
     * File content encryption and decryption capabilities.
51
     *
52
     * {@internal Reusable implementation of `FileEncryptionInterface`. }}
53
     */
54
    use EncryptFiles;
55
56
    /**
57
     * Cipher data outputting formats.
58
     *
59
     * {@internal Reusable implementation of `CipherDataFormatsInterface`. }}
60
     */
61
    use CipherDataFormats;
62
63
    /**
64
     * The internal name of the algorithm.
65
     */
66
    const ALGORITHM_NAME = OPENSSL_KEYTYPE_RSA;
67
68
    /**
69
     * The asymmetric data padding operation property.
70
     *
71
     * @var int The data padding operation integer code value.
72
     */
73
    protected $padding = self::OAEP_PADDING;
74
75
    /**
76
     * The output cipher format property storage.
77
     *
78
     * @var int The output cipher format integer code value.
79
     */
80
    protected $cipherFormat = self::ENCRYPTION_OUTPUT_BASE_64;
81
82
    /**
83
     * Flag for enabling/disabling data processing via chunks.
84
     *
85
     * @var bool Flag to for data processing via chunks.
86
     */
87
    protected $useChunks = false;
88
89
    /**
90
     * Internal method for the validation of plain data used at encryption/signing operations.
91
     *
92
     * @param string $plainData The plain input string.
93
     *
94
     * @throws \Exception Validation errors.
95
     */
96 81
    protected function validatePlainData($plainData)
97
    {
98 81
        if (!is_string($plainData)) {
99 4
            throw new \InvalidArgumentException("The data for encryption must be a string or a binary string.");
100 77
        } elseif ($this->useChunks === false) {
101 73
            $chunkSize = (int)ceil(static::KEY_SIZE / 8) - $this->getPaddingReservedSize();
102
103 73
            if (strlen($plainData) > $chunkSize) {
104 4
                throw new \InvalidArgumentException(
105 4
                    "The data for encryption must be less or equal of $chunkSize bytes. Another option is " .
106 4
                    "to allow chunk processing via the `enableChunkProcessing` method, which is not recommended."
107 4
                );
108
            }
109
        }
110
    }
111
112
    /**
113
     * Internal method for the validation of cipher/signature data used at decryption/verifying operations.
114
     *
115
     * @param string $cipherOrSignatureData The encrypted input string or a signature string.
116
     *
117
     * @throws \Exception Validation errors.
118
     */
119 60
    protected function validateCipherOrSignatureData($cipherOrSignatureData)
120
    {
121 60
        if (!is_string($cipherOrSignatureData)) {
122 5
            throw new \InvalidArgumentException("The data for decryption must be a string or a binary string.");
123 55
        } elseif ($cipherOrSignatureData === '') {
124 4
            throw new \InvalidArgumentException("The string is empty and there is nothing to decrypt from it.");
125
        }
126
127 51
        $chunkSize = (int)ceil(static::KEY_SIZE / 8);
128 51
        $rawDataSize = strlen($this->changeOutputFormat($cipherOrSignatureData, false));
129
130 51
        if ($this->useChunks === false && $rawDataSize > $chunkSize) {
131 4
            throw new \InvalidArgumentException(
132 4
                "The data for decryption must be less or equal of $chunkSize bytes. Another option is " .
133 4
                "to allow chunk processing via the `enableChunkProcessing` method, which is not recommended."
134 4
            );
135 47
        } elseif ($rawDataSize % $chunkSize !== 0) {
136 4
            throw new \InvalidArgumentException(
137 4
                "The data length for decryption must dividable by $chunkSize byte blocks."
138 4
            );
139
        }
140
    }
141
142
    /**
143
     * RSA asymmetric algorithm constructor.
144
     */
145 170
    public function __construct()
146
    {
147 170
    }
148
149
    /**
150
     * Get debug information for the class instance.
151
     *
152
     * @return array Debug information.
153
     */
154 4
    public function __debugInfo()
155
    {
156 4
        return [
157 4
            'standard' => 'RSA',
158 4
            'type' => 'asymmetrical encryption or public-key cipher',
159 4
            'key size in bits' => static::KEY_SIZE,
160 4
            'maximum input in bits' => static::KEY_SIZE - (($this->padding === OPENSSL_PKCS1_PADDING) ? 88 : 336),
161 4
            'is chunk processing enabled' => $this->useChunks,
162 4
            'padding standard' => $this->padding === self::OAEP_PADDING ? 'OAEP' : 'PKCS1',
163 4
            'private key' => $this->privateKey,
164 4
            'public key' => $this->publicKey,
165 4
        ];
166
    }
167
168
    /**
169
     * Encrypts the given plain data.
170
     *
171
     * @param string $plainData The plain input string.
172
     *
173
     * @return string The cipher/encrypted data.
174
     * @throws \Exception Validation errors.
175
     */
176 85
    public function encryptData($plainData)
177
    {
178 85
        $this->checkIfThePublicKeyIsSet();
179 81
        $this->validatePlainData($plainData);
180
181 73
        $publicKeyResource = openssl_pkey_get_public(base64_decode($this->publicKey));
182
183
        // @codeCoverageIgnoreStart
184
        if ($publicKeyResource === false) {
185
            throw new \RuntimeException(
186
                'Failed to use the current public key, probably because of ' .
187
                'a misconfigured OpenSSL library or an invalid key.'
188
            );
189
        }
190
        // @codeCoverageIgnoreEnd
191
192 73
        $chunkSize = (int)ceil(static::KEY_SIZE / 8) - $this->getPaddingReservedSize();
193 73
        $needsOnePass = ($plainData === '');
194 73
        $cipherData = '';
195
196 73
        while ($plainData || $needsOnePass) {
197 73
            $dataChunk = substr($plainData, 0, $chunkSize);
198 73
            $plainData = substr($plainData, $chunkSize);
199 73
            $encryptedChunk = '';
200
201 73
            if (!openssl_public_encrypt($dataChunk, $encryptedChunk, $publicKeyResource, $this->padding)) {
202 4
                throw new \InvalidArgumentException('The data encryption failed because of a wrong format');
203
            }
204
205 69
            $cipherData .= $encryptedChunk;
206 69
            $needsOnePass = false;
207
        }
208
209
        // Free the public key (resource cleanup)
210 69
        @openssl_free_key($publicKeyResource);
211 69
        $publicKeyResource = null;
212
213 69
        return $this->changeOutputFormat($cipherData, true);
214
    }
215
216
    /**
217
     * Decrypts the given cipher data.
218
     *
219
     * @param string $cipherData The encrypted input string.
220
     *
221
     * @return string The decrypted/plain data.
222
     * @throws \Exception Validation errors.
223
     */
224 64
    public function decryptData($cipherData)
225
    {
226 64
        $this->checkIfThePrivateKeyIsSet();
227 60
        $this->validateCipherOrSignatureData($cipherData);
228
229 43
        $cipherData = $this->changeOutputFormat($cipherData, false);
230 43
        $privateKeyResource = openssl_pkey_get_private(base64_decode($this->privateKey));
231
232
        // @codeCoverageIgnoreStart
233
        if ($privateKeyResource === false) {
234
            throw new \RuntimeException(
235
                'Failed to use the current private key, probably because of ' .
236
                'a misconfigured OpenSSL library or an invalid key.'
237
            );
238
        }
239
        // @codeCoverageIgnoreEnd
240
241
        /**
242
         * {@internal The block size must be exactly dividable by the chunks size. }}
243
         */
244 43
        $chunkSize = (int)ceil(static::KEY_SIZE / 8);
245 43
        $plainData = '';
246
247 43
        while ($cipherData) {
248 43
            $chunkData = substr($cipherData, 0, $chunkSize);
249 43
            $cipherData = substr($cipherData, $chunkSize);
250 43
            $decryptedChunk = '';
251
252 43
            if (!openssl_private_decrypt($chunkData, $decryptedChunk, $privateKeyResource, $this->padding)) {
253 4
                throw new \InvalidArgumentException('The data decryption failed because of a wrong format');
254
            }
255
256 39
            $plainData .= $decryptedChunk;
257
        }
258
259
        // Free the private key (resource cleanup)
260 39
        @openssl_free_key($privateKeyResource);
261 39
        $privateKeyResource = null;
262
263 39
        return $plainData;
264
    }
265
}
266