-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathstream_cipher_gcm.php
82 lines (72 loc) · 1.79 KB
/
stream_cipher_gcm.php
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
<?php
// INIT
// temporary file
$filename = tempnam(sys_get_temp_dir(), 'php_crypto_');
// use AES with CBC mode
$algorithm = 'aes-256-gcm';
$key = str_repeat('x', 32);
$iv = str_repeat('i', 16);
$data = str_repeat('a', 16);
// ---------------------------
// WRITE to the encrypted file
// create a stream context with cipher filter
$context_write = stream_context_create(array(
'crypto' => array(
'filters' => array(
array(
'type' => 'cipher',
'action' => 'encrypt',
'algorithm' => $algorithm,
'key' => $key,
'iv' => $iv,
)
)
),
));
$stream_write = fopen("crypto.file://" . $filename, "w", false, $context_write);
if (!$stream_write) {
exit;
}
fwrite($stream_write, $data);
fflush($stream_write);
echo "FILE '$filename' encrypted (base64):" . PHP_EOL;
echo base64_encode(file_get_contents($filename));
echo PHP_EOL;
echo "META FIELDS:" . PHP_EOL;
print_r(stream_get_meta_data($stream_write));
echo PHP_EOL;
// ---------------------------
// READ encrypted file
// create a stream context with cipher filter
$context_read = stream_context_create(array(
'crypto' => array(
'filters' => array(
array(
'type' => 'cipher',
'action' => 'decrypt',
'algorithm' => $algorithm,
'key' => $key,
'iv' => $iv,
'tag' => 'wrong',
)
)
),
));
echo "FILE '$filename' decrypted (plain):" . PHP_EOL;
$stream_read = fopen("crypto.file://" . $filename, "r", false, $context_read);
if (!$stream_read) {
exit;
}
while ($data = fread($stream_read, 5)) {
echo $data;
}
echo file_get_contents("crypto.file://" . $filename, false, $context_read);
echo PHP_EOL;
echo "META FIELDS:" . PHP_EOL;
print_r(stream_get_meta_data($stream_read));
echo PHP_EOL;
// ---------------------------
// DELETE the temporary file
if (unlink($filename)) {
echo "FILE '$filename' deleted" . PHP_EOL;
}