Completed
Push — master ( c93584...7286b1 )
by Francesco
04:37
created

EncryptionTest::testEncryptFileEncryptsFile()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
c 0
b 0
f 0
rs 8.8571
cc 1
eloc 17
nc 1
nop 0
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 Mes\Security\CryptoBundle\Encryption;
15
use Mes\Security\CryptoBundle\EncryptionInterface;
16
use Mes\Security\CryptoBundle\KeyGenerator\KeyGenerator;
17
use Mes\Security\CryptoBundle\KeyGenerator\KeyGeneratorInterface;
18
use Mes\Security\CryptoBundle\Model\KeyInterface;
19
20
/**
21
 * Class EncryptionTest.
22
 */
23
class EncryptionTest extends \PHPUnit_Framework_TestCase
24
{
25
    /**
26
     * @var EncryptionInterface
27
     */
28
    private $encryption;
29
30
    /**
31
     * @var KeyGeneratorInterface
32
     */
33
    private $generator;
34
35
    protected function setUp()
36
    {
37
        $this->encryption = new Encryption();
38
        $this->generator = new KeyGenerator();
39
    }
40
41
    protected function tearDown()
42
    {
43
        $this->encryption = null;
44
        $this->generator = null;
45
    }
46
47
    /**
48
     * @return array
49
     */
50
    public function testEncryptEncryptsPlaintext()
51
    {
52
        $key = $this->generator->generate();
53
        $plaintext = 'The quick brown fox jumps over the lazy dog';
54
        $ciphertext = $this->encryption->encrypt($plaintext, $key);
55
56
        $this->assertTrue(ctype_print($ciphertext), 'is printable');
57
58
        return array(
59
            'ciphertext' => $ciphertext,
60
            'key_encoded' => $key->getEncoded(),
61
        );
62
    }
63
64
    /**
65
     * @depends testEncryptEncryptsPlaintext
66
     *
67
     * @param $args
68
     */
69
    public function testDecryptDecryptsCiphertext($args)
70
    {
71
        $key = $this->generator->generateFromAscii($args['key_encoded']);
72
        $plaintext = $this->encryption->decrypt($args['ciphertext'], $key);
73
74
        $this->assertSame('The quick brown fox jumps over the lazy dog', $plaintext);
75
    }
76
77
    /**
78
     * @depends testEncryptEncryptsPlaintext
79
     *
80
     * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException
81
     *
82
     * @param $args
83
     */
84
    public function testDecryptThrowsExceptionBecauseCiphertextIsCorrupted($args)
85
    {
86
        $key = $this->generator->generateFromAscii($args['key_encoded']);
87
        $this->encryption->decrypt($args['ciphertext'].'{FakeString}', $key);
88
    }
89
90
    /**
91
     * @depends testEncryptEncryptsPlaintext
92
     *
93
     * @expectedException \Defuse\Crypto\Exception\BadFormatException
94
     *
95
     * @param $args
96
     */
97
    public function testDecryptThrowsExceptionBecauseKeyIsCorrupted($args)
98
    {
99
        $key = $this->generator->generateFromAscii($args['key_encoded'].'{FakeString}');
100
        $this->encryption->decrypt($args['ciphertext'], $key);
101
    }
102
103
    /**
104
     * @return array
105
     */
106
    public function testEncryptEncryptsPlaintextWithPassword()
107
    {
108
        $key = $this->generator->generate('ThisIsASecretPassword');
109
110
        $this->assertInstanceOf('\Defuse\Crypto\KeyProtectedByPassword', $key->getRawKey());
111
        $this->assertSame('ThisIsASecretPassword', $key->getSecret());
112
113
        $plaintext = 'The quick brown fox jumps over the lazy dog';
114
        $ciphertext = $this->encryption->encrypt($plaintext, $key);
115
116
        $this->assertInstanceOf('\Defuse\Crypto\Key', $key->getRawKey());
117
        $this->assertTrue(ctype_print($ciphertext), 'is printable');
118
        $this->assertTrue(ctype_print($key->getEncoded()), 'is printable');
119
120
        return array(
121
            'ciphertext' => $ciphertext,
122
            'key_encoded' => $key->getEncoded(),
123
            'secret' => $key->getSecret(),
124
        );
125
    }
126
127
    /**
128
     * @depends testEncryptEncryptsPlaintextWithPassword
129
     *
130
     * @param $args
131
     */
132
    public function testDecryptDecryptsCiphertextWithPassword($args)
133
    {
134
        $keyFromAscii = $this->generator->generateFromAscii($args['key_encoded'], $args['secret']);
135
136
        $this->assertInstanceOf('\Defuse\Crypto\KeyProtectedByPassword', $keyFromAscii->getRawKey());
137
        $this->assertSame($args['secret'], $keyFromAscii->getSecret());
138
139
        $plaintext = $this->encryption->decrypt($args['ciphertext'], $keyFromAscii);
140
141
        $this->assertSame('The quick brown fox jumps over the lazy dog', $plaintext);
142
    }
143
144
    /**
145
     * @depends testEncryptEncryptsPlaintextWithPassword
146
     *
147
     * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException
148
     *
149
     * @param $args
150
     */
151
    public function testDecryptThrowsExceptionWithCiphertextWithPasswordBecauseSecretIsCorrupted($args)
152
    {
153
        $keyFromAscii = $this->generator->generateFromAscii($args['key_encoded'], $args['secret'].'{FakeString}');
154
155
        $this->encryption->decrypt($args['ciphertext'], $keyFromAscii);
156
    }
157
158
    /**
159
     * @depends testEncryptEncryptsPlaintextWithPassword
160
     *
161
     * @expectedException \Defuse\Crypto\Exception\BadFormatException
162
     *
163
     * @param $args
164
     */
165
    public function testDecryptThrowsExceptionWithCiphertextWithPasswordBecauseKeyIsCorrupted($args)
166
    {
167
        $keyFromAscii = $this->generator->generateFromAscii($args['key_encoded'].'{FakeString}', $args['secret']);
168
169
        $this->encryption->decrypt($args['ciphertext'], $keyFromAscii);
170
    }
171
172
    /**
173
     * @depends testEncryptEncryptsPlaintextWithPassword
174
     *
175
     * @expectedException \Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException
176
     *
177
     * @param $args
178
     */
179
    public function testDecryptThrowsExceptionWithCiphertextWithPasswordBecauseCiphertextIsCorrupted($args)
180
    {
181
        $keyFromAscii = $this->generator->generateFromAscii($args['key_encoded'], $args['secret']);
182
183
        $this->encryption->decrypt($args['ciphertext'].'{FakeString}', $keyFromAscii);
184
    }
185
186
    /**
187
     * @return array
188
     */
189
    public function testEncryptFileEncryptsFile()
190
    {
191
        /** @var KeyInterface $key */
192
        $key = $this->generator->generate('CryptoSecret');
193
194
        // Create file to encrypt.
195
        $tmpfname = tempnam(__DIR__, 'CRYPTO_');
196
        $plainContent = "Dinanzi a me non fuor cose create se non etterne, e io etterno duro. Lasciate ogni speranza, voi ch'intrate.";
197
        $handle = fopen($tmpfname, 'w');
198
        fwrite($handle, $plainContent);
199
        fclose($handle);
200
201
        $filename = md5(uniqid());
202
        $encryptedFilename = __DIR__."/ENCRYPTED_$filename.crypto";
203
204
        $this->encryption->encryptFile($tmpfname, $encryptedFilename, $key);
205
206
        $this->assertFileExists($encryptedFilename, sprintf('%s file must exists', $encryptedFilename));
207
        $this->assertGreaterThan(0, (new \SplFileInfo($encryptedFilename))->getSize());
208
209
        unlink($tmpfname);
210
211
        return array(
212
            'key' => $key->getEncoded(),
213
            'secret' => $key->getSecret(),
214
            'encryptedFile' => $encryptedFilename,
215
        );
216
    }
217
218
    /**
219
     * @depends testEncryptFileEncryptsFile
220
     *
221
     * @param $args
222
     */
223
    public function testDecryptFileDecryptsEncryptedFile($args)
224
    {
225
        /** @var KeyInterface $key */
226
        $key = $this->generator->generateFromAscii($args['key'], $args['secret']);
227
228
        $tmpDecryptedFile = tempnam(__DIR__, '_CRYPTO');
229
230
        $this->encryption->decryptFile($args['encryptedFile'], $tmpDecryptedFile, $key);
231
232
        $this->assertFileExists($tmpDecryptedFile);
233
        $this->assertGreaterThan(0, (new \SplFileInfo($tmpDecryptedFile))->getSize());
234
        $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));
235
236
        unlink($tmpDecryptedFile);
237
        unlink($args['encryptedFile']);
238
    }
239
}
240