-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecureFileEncryptor.php
More file actions
302 lines (249 loc) · 11.2 KB
/
Copy pathSecureFileEncryptor.php
File metadata and controls
302 lines (249 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
declare(strict_types=1);
namespace CryptoFramework\FileEncryption;
use CryptoFramework\Exceptions\CryptoException;
use CryptoFramework\Exceptions\DecryptionException;
use CryptoFramework\Interfaces\SymmetricCryptoInterface;
use CryptoFramework\Symmetric\AES256GCM;
use CryptoFramework\Utils\RandomGenerator;
/**
* Classe para criptografia segura de arquivos
*/
final class SecureFileEncryptor
{
private const BUFFER_SIZE = 1024 * 1024; // 1MB
private const HEADER_MAGIC = 'SECFILE';
private const HEADER_VERSION = 1;
/**
* @param SymmetricCryptoInterface $cipher Cifra para criptografia
* @param RandomGenerator $randomGenerator Gerador de números aleatórios
*/
public function __construct(
private readonly SymmetricCryptoInterface $cipher = new AES256GCM(),
private readonly RandomGenerator $randomGenerator = new RandomGenerator()
) {
}
/**
* Criptografa um arquivo
*
* @param string $inputFile Caminho para o arquivo de entrada
* @param string $outputFile Caminho para o arquivo de saída
* @param string $key Chave de criptografia
* @param array<string, mixed> $metadata Metadados do arquivo
* @return bool True se o arquivo foi criptografado com sucesso
* @throws CryptoException
*/
public function encryptFile(string $inputFile, string $outputFile, string $key, array $metadata = []): bool
{
if (!file_exists($inputFile)) {
throw new CryptoException("Arquivo de entrada não encontrado: $inputFile");
}
try {
$inputHandle = fopen($inputFile, 'rb');
$outputHandle = fopen($outputFile, 'wb');
if ($inputHandle === false || $outputHandle === false) {
throw new CryptoException("Falha ao abrir arquivos");
}
// Gerar ID único para o arquivo
$fileId = $this->randomGenerator->generateUUID();
// Preparar metadados
$metadata['file_id'] = $fileId;
$metadata['created_at'] = time();
$metadata['original_size'] = filesize($inputFile);
$metadata['original_name'] = basename($inputFile);
// Serializar metadados
$metadataJson = json_encode($metadata);
if ($metadataJson === false) {
throw new CryptoException("Falha ao serializar metadados");
}
// Criptografar metadados
$encryptedMetadata = $this->cipher->encrypt($metadataJson, $key);
// Escrever cabeçalho
$header = pack(
'a7Cv',
self::HEADER_MAGIC,
self::HEADER_VERSION,
strlen($encryptedMetadata)
);
fwrite($outputHandle, $header);
fwrite($outputHandle, $encryptedMetadata);
// Processar o arquivo em blocos
while (!feof($inputHandle)) {
$data = fread($inputHandle, self::BUFFER_SIZE);
if ($data === false) {
throw new CryptoException("Falha ao ler arquivo de entrada");
}
if (strlen($data) > 0) {
$encryptedData = $this->cipher->encrypt($data, $key, $fileId);
$blockSize = strlen($encryptedData);
// Escrever tamanho do bloco e dados criptografados
fwrite($outputHandle, pack('N', $blockSize));
fwrite($outputHandle, $encryptedData);
}
}
// Fechar arquivos
fclose($inputHandle);
fclose($outputHandle);
return true;
} catch (\Exception $e) {
// Limpar arquivo de saída em caso de erro
if (isset($outputHandle) && $outputHandle !== false) {
fclose($outputHandle);
if (file_exists($outputFile)) {
unlink($outputFile);
}
}
if (isset($inputHandle) && $inputHandle !== false) {
fclose($inputHandle);
}
throw new CryptoException("Erro ao criptografar arquivo: " . $e->getMessage(), previous: $e);
}
}
/**
* Descriptografa um arquivo
*
* @param string $inputFile Caminho para o arquivo de entrada
* @param string $outputFile Caminho para o arquivo de saída
* @param string $key Chave de criptografia
* @return array<string, mixed> Metadados do arquivo
* @throws CryptoException|DecryptionException
*/
public function decryptFile(string $inputFile, string $outputFile, string $key): array
{
if (!file_exists($inputFile)) {
throw new CryptoException("Arquivo criptografado não encontrado: $inputFile");
}
try {
$inputHandle = fopen($inputFile, 'rb');
$outputHandle = fopen($outputFile, 'wb');
if ($inputHandle === false || $outputHandle === false) {
throw new CryptoException("Falha ao abrir arquivos");
}
// Ler cabeçalho
$header = fread($inputHandle, 9);
if ($header === false || strlen($header) < 9) {
throw new CryptoException("Arquivo criptografado inválido: cabeçalho incompleto");
}
$headerData = unpack('a7magic/Cversion/vmetadata_size', $header);
if ($headerData === false || $headerData['magic'] !== self::HEADER_MAGIC) {
throw new CryptoException("Arquivo criptografado inválido: assinatura incorreta");
}
if ($headerData['version'] !== self::HEADER_VERSION) {
throw new CryptoException("Versão de arquivo não suportada: " . $headerData['version']);
}
// Ler metadados criptografados
$encryptedMetadata = fread($inputHandle, $headerData['metadata_size']);
if ($encryptedMetadata === false || strlen($encryptedMetadata) < $headerData['metadata_size']) {
throw new CryptoException("Arquivo criptografado inválido: metadados incompletos");
}
// Descriptografar metadados
$metadataJson = $this->cipher->decrypt($encryptedMetadata, $key);
$metadata = json_decode($metadataJson, true);
if (!is_array($metadata) || !isset($metadata['file_id'])) {
throw new CryptoException("Metadados inválidos");
}
$fileId = $metadata['file_id'];
// Processar o arquivo em blocos
while (!feof($inputHandle)) {
// Ler tamanho do bloco
$blockSizeData = fread($inputHandle, 4);
if ($blockSizeData === false || strlen($blockSizeData) < 4) {
break; // Fim do arquivo
}
$blockSize = unpack('N', $blockSizeData)[1];
// Ler bloco criptografado
$encryptedData = fread($inputHandle, $blockSize);
if ($encryptedData === false || strlen($encryptedData) < $blockSize) {
throw new CryptoException("Arquivo criptografado inválido: dados incompletos");
}
// Descriptografar bloco
$data = $this->cipher->decrypt($encryptedData, $key, $fileId);
// Escrever dados descriptografados
fwrite($outputHandle, $data);
}
// Fechar arquivos
fclose($inputHandle);
fclose($outputHandle);
return $metadata;
} catch (\Exception $e) {
// Limpar arquivo de saída em caso de erro
if (isset($outputHandle) && $outputHandle !== false) {
fclose($outputHandle);
if (file_exists($outputFile)) {
unlink($outputFile);
}
}
if (isset($inputHandle) && $inputHandle !== false) {
fclose($inputHandle);
}
throw new CryptoException("Erro ao descriptografar arquivo: " . $e->getMessage(), previous: $e);
}
}
/**
* Verifica se um arquivo está criptografado
*
* @param string $file Caminho para o arquivo
* @return bool True se o arquivo estiver criptografado
*/
public function isEncryptedFile(string $file): bool
{
if (!file_exists($file)) {
return false;
}
try {
$handle = fopen($file, 'rb');
if ($handle === false) {
return false;
}
$header = fread($handle, 7);
fclose($handle);
return $header === self::HEADER_MAGIC;
} catch (\Exception $e) {
return false;
}
}
/**
* Lê os metadados de um arquivo criptografado sem descriptografá-lo
*
* @param string $file Caminho para o arquivo
* @param string $key Chave de criptografia
* @return array<string, mixed> Metadados do arquivo
* @throws CryptoException
*/
public function readFileMetadata(string $file, string $key): array
{
if (!file_exists($file)) {
throw new CryptoException("Arquivo não encontrado: $file");
}
try {
$handle = fopen($file, 'rb');
if ($handle === false) {
throw new CryptoException("Falha ao abrir arquivo");
}
// Ler cabeçalho
$header = fread($handle, 9);
if ($header === false || strlen($header) < 9) {
throw new CryptoException("Arquivo criptografado inválido: cabeçalho incompleto");
}
$headerData = unpack('a7magic/Cversion/vmetadata_size', $header);
if ($headerData === false || $headerData['magic'] !== self::HEADER_MAGIC) {
throw new CryptoException("Arquivo criptografado inválido: assinatura incorreta");
}
// Ler metadados criptografados
$encryptedMetadata = fread($handle, $headerData['metadata_size']);
fclose($handle);
if ($encryptedMetadata === false || strlen($encryptedMetadata) < $headerData['metadata_size']) {
throw new CryptoException("Arquivo criptografado inválido: metadados incompletos");
}
// Descriptografar metadados
$metadataJson = $this->cipher->decrypt($encryptedMetadata, $key);
$metadata = json_decode($metadataJson, true);
if (!is_array($metadata)) {
throw new CryptoException("Metadados inválidos");
}
return $metadata;
} catch (\Exception $e) {
throw new CryptoException("Erro ao ler metadados: " . $e->getMessage(), previous: $e);
}
}
}