Completed
Push — master ( 2e6254...ddfae3 )
by Tony Karavasilev (Тони
16:43
created

AbstractRsaEncryption   A

Complexity

Total Complexity 23

Size/Duplication

Total Lines 235
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 23
eloc 85
c 1
b 0
f 0
dl 0
loc 235
ccs 71
cts 71
cp 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A validateCipherOrSignatureData() 0 19 6
A __debugInfo() 0 11 3
A encryptData() 0 38 5
A validatePlainData() 0 11 4
A __construct() 0 2 1
A decryptData() 0 40 4
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 152
    protected function validatePlainData($plainData)
97
    {
98 152
        if (!is_string($plainData)) {
99 8
            throw new \InvalidArgumentException('The data for encryption must be a string or a binary string.');
100 144
        } elseif ($this->useChunks === false) {
101 136
            $chunkSize = (int)ceil(static::KEY_SIZE / 8) - $this->getPaddingReservedSize();
102
103 136
            if (strlen($plainData) > $chunkSize) {
104 8
                throw new \InvalidArgumentException(
105 8
                    'The data for encryption must be less or equal of ' . $chunkSize . ' bytes. Another option is ' .
106 8
                    'to allow chunk processing via the `enableChunkProcessing` method, which is not recommended.'
107
                );
108
            }
109
        }
110 136
    }
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 112
    protected function validateCipherOrSignatureData($cipherOrSignatureData)
120
    {
121 112
        if (!is_string($cipherOrSignatureData)) {
122 8
            throw new \InvalidArgumentException('The data for decryption must be a string or a binary string.');
123 104
        } elseif ($cipherOrSignatureData === '') {
124 8
            throw new \InvalidArgumentException('The string is empty and there is nothing to decrypt from it.');
125
        }
126
127 96
        $chunkSize = (int)ceil(static::KEY_SIZE / 8);
128 96
        $rawDataSize = strlen($this->changeOutputFormat($cipherOrSignatureData, false));
129
130 96
        if ($this->useChunks === false && $rawDataSize > $chunkSize) {
131 8
            throw new \InvalidArgumentException(
132 4
                'The data for decryption must be less or equal of ' . $chunkSize . ' bytes. Another option is ' .
133 8
                'to allow chunk processing via the `enableChunkProcessing` method, which is not recommended.'
134
            );
135 88
        } elseif ($rawDataSize % $chunkSize !== 0) {
136 8
            throw new \InvalidArgumentException(
137 8
                'The data length for decryption must dividable by ' . $chunkSize . ' byte blocks.'
138
            );
139
        }
140 80
    }
141
142
    /**
143
     * Encrypts the given plain data.
144
     *
145
     * @param string $plainData The plain input string.
146
     *
147
     * @return string The cipher/encrypted data.
148
     * @throws \Exception Validation errors.
149
     */
150 160
    public function encryptData($plainData)
151
    {
152 160
        $this->checkIfThePublicKeyIsSet();
153 152
        $this->validatePlainData($plainData);
154
155 136
        $publicKeyResource = openssl_pkey_get_public(base64_decode($this->publicKey));
156
157
        // @codeCoverageIgnoreStart
158
        if ($publicKeyResource === false) {
159
            throw new \RuntimeException(
160
                'Failed to use the current public key, probably because of ' .
161
                'a misconfigured OpenSSL library or an invalid key.'
162
            );
163
        }
164
        // @codeCoverageIgnoreEnd
165
166 136
        $chunkSize = (int)ceil(static::KEY_SIZE / 8) - $this->getPaddingReservedSize();
167 136
        $needsOnePass = ($plainData === '');
168 136
        $cipherData = '';
169
170 136
        while ($plainData || $needsOnePass) {
171 136
            $dataChunk = substr($plainData, 0, $chunkSize);
172 136
            $plainData = substr($plainData, $chunkSize);
173 136
            $encryptedChunk = '';
174
175 136
            if (!openssl_public_encrypt($dataChunk, $encryptedChunk, $publicKeyResource, $this->padding)) {
176 8
                throw new \InvalidArgumentException('The data encryption failed because of a wrong format');
177
            }
178
179 128
            $cipherData .= $encryptedChunk;
180 128
            $needsOnePass = false;
181
        }
182
183
        // Free the public key (resource cleanup)
184 128
        openssl_free_key($publicKeyResource);
185 128
        $publicKeyResource = null;
186
187 128
        return $this->changeOutputFormat($cipherData, true);
188
    }
189
190
    /**
191
     * Decrypts the given cipher data.
192
     *
193
     * @param string $cipherData The encrypted input string.
194
     *
195
     * @return string The decrypted/plain data.
196
     * @throws \Exception Validation errors.
197
     */
198 120
    public function decryptData($cipherData)
199
    {
200 120
        $this->checkIfThePrivateKeyIsSet();
201 112
        $this->validateCipherOrSignatureData($cipherData);
202
203 80
        $cipherData = $this->changeOutputFormat($cipherData, false);
204 80
        $privateKeyResource = openssl_pkey_get_private(base64_decode($this->privateKey));
205
206
        // @codeCoverageIgnoreStart
207
        if ($privateKeyResource === false) {
208
            throw new \RuntimeException(
209
                'Failed to use the current private key, probably because of ' .
210
                'a misconfigured OpenSSL library or an invalid key.'
211
            );
212
        }
213
        // @codeCoverageIgnoreEnd
214
215
        /**
216
         * {@internal The block size must be exactly dividable by the chunks size. }}
217
         */
218 80
        $chunkSize = (int)ceil(static::KEY_SIZE / 8);
219 80
        $plainData = '';
220
221 80
        while ($cipherData) {
222 80
            $chunkData = substr($cipherData, 0, $chunkSize);
223 80
            $cipherData = substr($cipherData, $chunkSize);
224 80
            $decryptedChunk = '';
225
226 80
            if (!openssl_private_decrypt($chunkData, $decryptedChunk, $privateKeyResource, $this->padding)) {
227 8
                throw new \InvalidArgumentException('The data decryption failed because of a wrong format');
228
            }
229
230 72
            $plainData .= $decryptedChunk;
231
        }
232
233
        // Free the private key (resource cleanup)
234 72
        openssl_free_key($privateKeyResource);
235 72
        $privateKeyResource = null;
236
237 72
        return $plainData;
238
    }
239
240
    /**
241
     * RSA asymmetric algorithm constructor.
242
     */
243 296
    public function __construct()
244
    {
245 296
    }
246
247
    /**
248
     * Get debug information for the class instance.
249
     *
250
     * @return array Debug information.
251
     */
252 8
    public function __debugInfo()
253
    {
254
        return [
255 8
            'standard' => 'RSA',
256 8
            'type' => 'asymmetrical encryption or public-key cipher',
257 8
            'key size in bits' => static::KEY_SIZE,
258 8
            'maximum input in bits' => static::KEY_SIZE - (($this->padding === OPENSSL_PKCS1_PADDING) ? 88 : 336),
259 8
            'is chunk processing enabled' => $this->useChunks,
260 8
            'padding standard' => $this->padding === self::OAEP_PADDING ? 'OAEP' : 'PKCS1',
261 8
            'private key' => $this->privateKey,
262 8
            'public key' => $this->publicKey,
263
        ];
264
    }
265
}
266