What is the best way to encrypt files in AES-256 using PHP?

I found several online tutorials that might help, but I'm not sure if there are better options. I would like to encrypt the file using a highly secure algorithm (I'm a little paranoid), but at the same time I'm looking for speed (I know this is a bit of a contradiction) ... So I chose AES-256 ... But what is the best way to use AES- 256 with PHP for file encryption?

+5
source share
2 answers

PHP 5.x and 7.0.x

For a symmetric algorithm, use Mcrypt .

, , , , , . .

(, ).

PHP 7.1.x +

Mcrypt 7.1 7.2, . Sodium.

+6

PHP Mcrypt AES-256 ( IV 16 ) sha256 hmac :

<?php
print_r(mcrypt_list_algorithms());//check if rijndael-128 available
print_r(stream_get_filters());    //should contain mcrypt.* and mdecrypt.*

//16 byte key=>AES-128, 24 byte key=>AES-192, 32 byte key=>AES-256
$key='BkK8Jts................sPo38nNcW';

//encrypt file
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_RANDOM);//or MCRYPT_DEV_URANDOM
$fin = fopen($in_filename, "rb");
$fcrypt = fopen($aes_filename, 'wb');
fwrite($fcrypt, $iv);
$opts = array('iv'=>$iv, 'key'=>$key, 'mode'=>'cbc');
stream_filter_append($fcrypt, 'mcrypt.rijndael-128', STREAM_FILTER_WRITE, $opts);
while (!feof($fin))
{
    fwrite($fcrypt, fread($fin, 8192));
}
fclose($fcrypt);
fclose($fin);
$hmac_real = hash_hmac_file('sha256', $aes_filename, $key, $raw=false);

//decrypt file
$hmac_calc = hash_hmac_file('sha256', $aes_filename, $key, $raw=false);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$fcrypt = fopen($aes_filename, "rb");
$fout = fopen($out_filename, 'wb');
$iv = fread($fcrypt, $iv_size);
$opts = array('iv'=>$iv, 'key'=>$key, 'mode'=>'cbc');
stream_filter_append($fcrypt, 'mdecrypt.rijndael-128', STREAM_FILTER_READ, $opts);
while (!feof($fcrypt))
{
    $block = fread($fcrypt, 8192);
    $block = feof($fcrypt)? rtrim($block,"\0") : $block;//removes aes pad
    fwrite($fout, $block);
}
fclose($fout);
fclose($fcrypt);
$hmac_calc==$hmac_real or unlink($out_filename);//invalid if they don't match

. http://php.net/manual/en/filters.encryption.php

AES-256 , 16- AES-128 . https://www.schneier.com/blog/archives/2009/07/another_new_aes.html

-1

All Articles