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-cbc'; 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; 40 41 42// --------------------------- 43// READ encrypted file 44 45// create a stream context with cipher filter 46$context_read = stream_context_create(array( 47 'crypto' => array( 48 'filters' => array( 49 array( 50 'type' => 'cipher', 51 'action' => 'decrypt', 52 'algorithm' => $algorithm, 53 'key' => $key, 54 'iv' => $iv, 55 ) 56 ) 57 ), 58)); 59echo "FILE '$filename' decrypted (plain):" . PHP_EOL; 60$stream_read = fopen("crypto.file://" . $filename, "r", false, $context_read); 61if (!$stream_read) { 62 exit; 63} 64while ($data = fread($stream_read, 5)) { 65 echo $data; 66} 67echo file_get_contents("crypto.file://" . $filename, false, $context_read); 68echo PHP_EOL; 69 70 71// --------------------------- 72// DELETE the temporary file 73if (unlink($filename)) { 74 echo "FILE '$filename' deleted" . PHP_EOL; 75} 76