1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SGP\IronBox\Encryption; |
4
|
|
|
|
5
|
|
|
use Exception; |
6
|
|
|
use SGP\IronBox\ContainerKeyData; |
7
|
|
|
use SGP\IronBox\Exceptions\IronBoxException; |
8
|
|
|
|
9
|
|
|
class FileEncrypter |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var string |
13
|
|
|
*/ |
14
|
|
|
protected $inputFile; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var string |
18
|
|
|
*/ |
19
|
|
|
protected $outputFile; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var \SGP\IronBox\Encryption\Encrypter |
23
|
|
|
*/ |
24
|
|
|
protected $encrypter; |
25
|
|
|
|
26
|
|
|
public function __construct($inputFile, $outputFile, ContainerKeyData $containerKeyData) |
27
|
|
|
{ |
28
|
|
|
$this->inputFile = $inputFile; |
29
|
|
|
$this->outputFile = $outputFile; |
30
|
|
|
|
31
|
|
|
$containerKeyData->validate(); |
32
|
|
|
|
33
|
|
|
$this->encrypter = new Encrypter( |
34
|
|
|
$containerKeyData->symmetricKey, |
|
|
|
|
35
|
|
|
$containerKeyData->cipher, |
|
|
|
|
36
|
|
|
$containerKeyData->initializationVector |
|
|
|
|
37
|
|
|
); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Encrypts a file using the symmetric key data. |
42
|
|
|
* |
43
|
|
|
* @return bool |
44
|
|
|
* @throws \SGP\IronBox\Exceptions\IronBoxException |
45
|
|
|
*/ |
46
|
|
|
public function encrypt() |
47
|
|
|
{ |
48
|
|
|
try { |
49
|
|
|
$readBlockSize = 1024; |
50
|
|
|
|
51
|
|
|
$in = fopen($this->inputFile, 'rb'); |
52
|
|
|
$out = fopen($this->outputFile, 'wb'); |
53
|
|
|
|
54
|
|
|
while (! feof($in)) { |
|
|
|
|
55
|
|
|
$line = fread($in, $readBlockSize); |
|
|
|
|
56
|
|
|
|
57
|
|
|
if (strlen($line) < $readBlockSize) { |
58
|
|
|
$line = $this->pad($line, $readBlockSize); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
fwrite($out, $this->encrypter->encrypt($line)); |
|
|
|
|
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
fclose($in); |
|
|
|
|
65
|
|
|
|
66
|
|
|
fclose($out); |
67
|
|
|
|
68
|
|
|
return true; |
69
|
|
|
} catch (Exception $e) { |
70
|
|
|
throw new IronBoxException('Unable to encrypt local copy of file', 0, $e); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* Pad a string to a certain length with another string. |
76
|
|
|
* |
77
|
|
|
* @param string $input |
78
|
|
|
* @param int $size |
79
|
|
|
* |
80
|
|
|
* @return string |
81
|
|
|
*/ |
82
|
|
|
private function pad(string $input, int $size) |
83
|
|
|
{ |
84
|
|
|
return str_pad($input, strlen($input) + ($size - strlen($input) % $size), chr(16 - strlen($input) % $size)); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|