1<?php 2 3// INIT 4 5// temporary file 6$filename = tempnam(sys_get_temp_dir(), 'php_crypto_'); 7// use AES with CBC mode 8$algorithm = 'aes-256-gcm'; 9$key = str_repeat('x', 32); 10$iv = str_repeat('i', 16); 11$data = str_repeat('a', 16); 12 13 14// --------------------------- 15// WRITE to the encrypted file 16 17// create a stream context with cipher filter 18$context_write = stream_context_create(array( 19 'crypto' => array( 20 'filters' => array( 21 array( 22 'type' => 'cipher', 23 'action' => 'encrypt', 24 'algorithm' => $algorithm, 25 'key' => $key, 26 'iv' => $iv, 27 ) 28 ) 29 ), 30)); 31$stream_write = fopen("crypto.file://" . $filename, "w", false, $context_write); 32if (!$stream_write) { 33 exit; 34} 35fwrite($stream_write, $data); 36fflush($stream_write); 37echo "FILE '$filename' encrypted (base64):" . PHP_EOL; 38echo base64_encode(file_get_contents($filename)); 39echo PHP_EOL; 40echo "META FIELDS:" . PHP_EOL; 41print_r(stream_get_meta_data($stream_write)); 42echo PHP_EOL; 43 44 45// --------------------------- 46// READ encrypted file 47 48// create a stream context with cipher filter 49$context_read = stream_context_create(array( 50 'crypto' => array( 51 'filters' => array( 52 array( 53 'type' => 'cipher', 54 'action' => 'decrypt', 55 'algorithm' => $algorithm, 56 'key' => $key, 57 'iv' => $iv, 58 'tag' => 'wrong', 59 ) 60 ) 61 ), 62)); 63echo "FILE '$filename' decrypted (plain):" . PHP_EOL; 64$stream_read = fopen("crypto.file://" . $filename, "r", false, $context_read); 65if (!$stream_read) { 66 exit; 67} 68while ($data = fread($stream_read, 5)) { 69 echo $data; 70} 71echo file_get_contents("crypto.file://" . $filename, false, $context_read); 72echo PHP_EOL; 73echo "META FIELDS:" . PHP_EOL; 74print_r(stream_get_meta_data($stream_read)); 75echo PHP_EOL; 76 77 78// --------------------------- 79// DELETE the temporary file 80if (unlink($filename)) { 81 echo "FILE '$filename' deleted" . PHP_EOL; 82}