Completed
Push — master ( 5132c9...a70667 )
by Francesco
03:24
created

EncryptionTest::testDecryptWithPasswordThrowsException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the MesCryptoBundle package.
5
 *
6
 * (c) Francesco Cartenì <http://www.multimediaexperiencestudio.it/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Mes\Security\CryptoBundle\Tests;
13
14
use Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException;
15
use Mes\Security\CryptoBundle\Encryption;
16
use Mes\Security\CryptoBundle\EncryptionInterface;
17
use Mes\Security\CryptoBundle\KeyGenerator\KeyGenerator;
18
use Mes\Security\CryptoBundle\KeyGenerator\KeyGeneratorInterface;
19
use Mes\Security\CryptoBundle\Model\KeyInterface;
20
use PHPUnit\Framework\TestCase;
21
22
/**
23
 * Class EncryptionTest.
24
 */
25
class EncryptionTest extends TestCase
26
{
27
    /**
28
     * @var EncryptionInterface
29
     */
30
    private $encryption;
31
32
    /**
33
     * @var KeyGeneratorInterface
34
     */
35
    private $generator;
36
37
    /**
38
     * @return array
39
     */
40
    public function testEncryptWithKeyEncryptsPlaintext()
41
    {
42
        $key = $this->generator->generate();
43
        $plaintext = 'The quick brown fox jumps over the lazy dog';
44
        $ciphertext = $this->encryption->encryptWithKey($plaintext, $key);
45
46
        $this->assertTrue(ctype_print($ciphertext), 'is printable');
47
48
        return array(
49
            'ciphertext' => $ciphertext,
50
            'key_encoded' => $key->getEncoded(),
51
        );
52
    }
53
54
    /**
55
     * @depends testEncryptWithKeyEncryptsPlaintext
56
     *
57
     * @param $args
58
     */
59
    public function testDecryptWithKeyDecryptsCiphertext($args)
60
    {
61
        $key = $this->generator->generateFromAscii($args['key_encoded']);
62
        $plaintext = $this->encryption->decryptWithKey($args['ciphertext'], $key);
63
64
        $this->assertSame('The quick brown fox jumps over the lazy dog', $plaintext);
65
    }
66
67
    /**
68
     * @depends testEncryptWithKeyEncryptsPlaintext
69
     *
70
     * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException
71
     *
72
     * @param $args
73
     */
74
    public function testDecryptThrowsExceptionBecauseCiphertextIsCorrupted($args)
75
    {
76
        $key = $this->generator->generateFromAscii($args['key_encoded']);
77
        $this->encryption->decryptWithKey($args['ciphertext'].'{FakeString}', $key);
78
    }
79
80
    /**
81
     * @depends testEncryptWithKeyEncryptsPlaintext
82
     *
83
     * @expectedException \Defuse\Crypto\Exception\BadFormatException
84
     *
85
     * @param $args
86
     */
87
    public function testDecryptWithKeyThrowsExceptionBecauseKeyIsCorrupted($args)
88
    {
89
        $key = $this->generator->generateFromAscii($args['key_encoded'].'{FakeString}');
90
        $this->encryption->decryptWithKey($args['ciphertext'], $key);
91
    }
92
93
    /**
94
     * @return array
95
     */
96
    public function testEncryptWithKeyEncryptsPlaintextWithPassword()
97
    {
98
        $key = $this->generator->generate('ThisIsASecretPassword');
99
100
        $this->assertInstanceOf('\Defuse\Crypto\KeyProtectedByPassword', $key->getRawKey());
101
        $this->assertSame('ThisIsASecretPassword', $key->getSecret());
102
103
        $plaintext = 'The quick brown fox jumps over the lazy dog';
104
        $ciphertext = $this->encryption->encryptWithKey($plaintext, $key);
105
106
        $this->assertInstanceOf('\Defuse\Crypto\Key', $key->getRawKey());
107
        $this->assertTrue(ctype_print($ciphertext), 'is printable');
108
        $this->assertTrue(ctype_print($key->getEncoded()), 'is printable');
109
110
        return array(
111
            'ciphertext' => $ciphertext,
112
            'key_encoded' => $key->getEncoded(),
113
            'secret' => $key->getSecret(),
114
        );
115
    }
116
117
    /**
118
     * @depends testEncryptWithKeyEncryptsPlaintextWithPassword
119
     *
120
     * @param $args
121
     */
122
    public function testDecryptWithKeyDecryptsCiphertextWithPassword($args)
123
    {
124
        $keyFromAscii = $this->generator->generateFromAscii($args['key_encoded'], $args['secret']);
125
126
        $this->assertInstanceOf('\Defuse\Crypto\KeyProtectedByPassword', $keyFromAscii->getRawKey());
127
        $this->assertSame($args['secret'], $keyFromAscii->getSecret());
128
129
        $plaintext = $this->encryption->decryptWithKey($args['ciphertext'], $keyFromAscii);
130
131
        $this->assertSame('The quick brown fox jumps over the lazy dog', $plaintext);
132
    }
133
134
    /**
135
     * @depends testEncryptWithKeyEncryptsPlaintextWithPassword
136
     *
137
     * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException
138
     *
139
     * @param $args
140
     */
141
    public function testDecryptWithKeyThrowsExceptionWithCiphertextWithPasswordBecauseSecretIsCorrupted($args)
142
    {
143
        $keyFromAscii = $this->generator->generateFromAscii($args['key_encoded'], $args['secret'].'{FakeString}');
144
145
        $this->encryption->decryptWithKey($args['ciphertext'], $keyFromAscii);
146
    }
147
148
    /**
149
     * @depends testEncryptWithKeyEncryptsPlaintextWithPassword
150
     *
151
     * @expectedException \Defuse\Crypto\Exception\BadFormatException
152
     *
153
     * @param $args
154
     */
155
    public function testDecryptWithKeyThrowsExceptionWithCiphertextWithPasswordBecauseKeyIsCorrupted($args)
156
    {
157
        $keyFromAscii = $this->generator->generateFromAscii($args['key_encoded'].'{FakeString}', $args['secret']);
158
159
        $this->encryption->decryptWithKey($args['ciphertext'], $keyFromAscii);
160
    }
161
162
    /**
163
     * @depends testEncryptWithKeyEncryptsPlaintextWithPassword
164
     *
165
     * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException
166
     *
167
     * @param $args
168
     */
169
    public function testDecryptWithKeyThrowsExceptionWithCiphertextWithPasswordBecauseCiphertextIsCorrupted($args)
170
    {
171
        $keyFromAscii = $this->generator->generateFromAscii($args['key_encoded'], $args['secret']);
172
173
        $this->encryption->decryptWithKey($args['ciphertext'].'{FakeString}', $keyFromAscii);
174
    }
175
176
    /**
177
     * @return array
178
     */
179
    public function testEncryptWithKeyFileEncryptsFile()
180
    {
181
        /** @var KeyInterface $key */
182
        $key = $this->generator->generate('CryptoSecret');
183
184
        // Create file to encrypt.
185
        $tmpfname = tempnam(__DIR__, 'CRYPTO_');
186
        $plainContent = "Dinanzi a me non fuor cose create se non etterne, e io etterno duro. Lasciate ogni speranza, voi ch'intrate.";
187
        $handle = fopen($tmpfname, 'w');
188
        fwrite($handle, $plainContent);
189
        fclose($handle);
190
191
        $filename = md5(uniqid());
192
        $encryptedFilename = __DIR__."/ENCRYPTED_$filename.crypto";
193
194
        $this->encryption->encryptFileWithKey($tmpfname, $encryptedFilename, $key);
195
196
        $this->assertFileExists($encryptedFilename, sprintf('%s file must exists', $encryptedFilename));
197
        $this->assertGreaterThan(0, (new \SplFileInfo($encryptedFilename))->getSize());
198
199
        unlink($tmpfname);
200
201
        return array(
202
            'key' => $key->getEncoded(),
203
            'secret' => $key->getSecret(),
204
            'encryptedFile' => $encryptedFilename,
205
        );
206
    }
207
208
    /**
209
     * @depends testEncryptWithKeyFileEncryptsFile
210
     *
211
     * @param $args
212
     */
213
    public function testDecryptWithKeyFileDecryptsEncryptedFile($args)
214
    {
215
        /** @var KeyInterface $key */
216
        $key = $this->generator->generateFromAscii($args['key'], $args['secret']);
217
218
        $tmpDecryptedFile = tempnam(__DIR__, '_CRYPTO');
219
220
        $this->encryption->decryptFileWithKey($args['encryptedFile'], $tmpDecryptedFile, $key);
221
222
        $this->assertFileExists($tmpDecryptedFile);
223
        $this->assertGreaterThan(0, (new \SplFileInfo($tmpDecryptedFile))->getSize());
224
        $this->assertContains("Dinanzi a me non fuor cose create se non etterne, e io etterno duro. Lasciate ogni speranza, voi ch'intrate.", file_get_contents($tmpDecryptedFile));
225
226
        unlink($tmpDecryptedFile);
227
        unlink($args['encryptedFile']);
228
    }
229
230
    /**
231
     * @return array
232
     */
233
    public function testEncryptWithPasswordEncryptsPlaintext()
234
    {
235
        $plaintext = 'The quick brown fox jumps over the lazy dog';
236
        $ciphertext = $this->encryption->encryptWithPassword($plaintext, 'SuperSecretPa$$word');
237
238
        $this->assertTrue(ctype_print($ciphertext), 'is printable');
239
240
        return array(
241
            'ciphertext' => $ciphertext,
242
        );
243
    }
244
245
    /**
246
     * @depends testEncryptWithPasswordEncryptsPlaintext
247
     *
248
     * @param $args
249
     */
250
    public function testDecryptWithPasswordDecryptsCiphertext($args)
251
    {
252
        $plaintext = $this->encryption->decryptWithPassword($args['ciphertext'], 'SuperSecretPa$$word');
253
254
        $this->assertSame('The quick brown fox jumps over the lazy dog', $plaintext, sprintf("'%s' is correct.", $plaintext));
255
    }
256
257
    /**
258
     * @depends testEncryptWithPasswordEncryptsPlaintext
259
     *
260
     * @param $args
261
     */
262
    public function testDecryptWithPasswordThrowsException($args)
263
    {
264
        $this->expectException(WrongKeyOrModifiedCiphertextException::class);
265
266
        $this->encryption->decryptWithPassword($args['ciphertext'], 'SuperSecretPa$$wordIncorrect');
267
    }
268
269
    /**
270
     * @return array
271
     */
272
    public function testEncryptFileWithPasswordEncryptsFile()
273
    {
274
        // Create file to encrypt.
275
        $tmpfname = tempnam(__DIR__, 'CRYPTO_');
276
        $plainContent = "Dinanzi a me non fuor cose create se non etterne, e io etterno duro. Lasciate ogni speranza, voi ch'intrate.";
277
        $handle = fopen($tmpfname, 'w');
278
        fwrite($handle, $plainContent);
279
        fclose($handle);
280
281
        $filename = md5(uniqid());
282
        $encryptedFilename = __DIR__."/ENCRYPTED_$filename.crypto";
283
284
        $this->encryption->encryptFileWithPassword($tmpfname, $encryptedFilename, 'SuperSecretPa$$word');
285
286
        $this->assertFileExists($encryptedFilename, sprintf('%s file must exists', $encryptedFilename));
287
        $this->assertGreaterThan(0, (new \SplFileInfo($encryptedFilename))->getSize());
288
289
        unlink($tmpfname);
290
291
        return array(
292
            'encryptedFile' => $encryptedFilename,
293
        );
294
    }
295
296
    /**
297
     * @depends testEncryptFileWithPasswordEncryptsFile
298
     *
299
     * @param $args
300
     */
301
    public function testDecryptFileWithPasswordDecryptsEncryptedFile($args)
302
    {
303
        $tmpDecryptedFile = tempnam(__DIR__, '_CRYPTO');
304
305
        $this->encryption->decryptFileWithPassword($args['encryptedFile'], $tmpDecryptedFile, 'SuperSecretPa$$word');
306
307
        $this->assertFileExists($tmpDecryptedFile);
308
        $this->assertGreaterThan(0, (new \SplFileInfo($tmpDecryptedFile))->getSize());
309
        $this->assertContains("Dinanzi a me non fuor cose create se non etterne, e io etterno duro. Lasciate ogni speranza, voi ch'intrate.", file_get_contents($tmpDecryptedFile));
310
311
        unlink($tmpDecryptedFile);
312
    }
313
314
    /**
315
     * @depends testEncryptFileWithPasswordEncryptsFile
316
     *
317
     * @param $args
318
     *
319
     * @throws \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException
320
     */
321
    public function testDecryptFileWithPasswordThrowsExceptionDecryptsEncryptedFile($args)
322
    {
323
        $this->expectException(WrongKeyOrModifiedCiphertextException::class);
324
325
        $tmpDecryptedFile = tempnam(__DIR__, '_CRYPTO');
326
327
        try {
328
            $this->encryption->decryptFileWithPassword($args['encryptedFile'], $tmpDecryptedFile, 'SuperSecretPa$$wordIncorrect');
329
        } catch (WrongKeyOrModifiedCiphertextException $e) {
330
            unlink($tmpDecryptedFile);
331
            unlink($args['encryptedFile']);
332
333
            throw $e;
334
        }
335
    }
336
337
    protected function setUp()
338
    {
339
        $this->encryption = new Encryption();
340
        $this->generator = new KeyGenerator();
341
    }
342
343
    protected function tearDown()
344
    {
345
        $this->encryption = null;
346
        $this->generator = null;
347
    }
348
}
349