Skip to content

Instantly share code, notes, and snippets.

@donaldsteele
Created January 19, 2022 02:33
Show Gist options
  • Save donaldsteele/6bcd2159cbcfc26696c2ff7408b80a9e to your computer and use it in GitHub Desktop.
Save donaldsteele/6bcd2159cbcfc26696c2ff7408b80a9e to your computer and use it in GitHub Desktop.
php aes 256 encryption example
<?php
define('FILE_ENCRYPTION_BLOCKS', 10000);
/**
* @param $source Path of the unencrypted file
* @param $dest Path of the encrypted file to created
* @param $key Encryption key
*/
function encryptFile($source, $dest, $key)
{
$cipher = 'aes-256-cbc';
$ivLenght = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivLenght);
$fpSource = fopen($source, 'rb');
$fpDest = fopen($dest, 'w');
fwrite($fpDest, $iv);
while (! feof($fpSource)) {
$plaintext = fread($fpSource, $ivLenght * FILE_ENCRYPTION_BLOCKS);
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, OPENSSL_RAW_DATA, $iv);
$iv = substr($ciphertext, 0, $ivLenght);
fwrite($fpDest, $ciphertext);
}
fclose($fpSource);
fclose($fpDest);
}
encryptFile('file.mp4', 'encrypted_file.mp4', 'my-secret-key');
echo "File encrypted!\n";
echo 'Memory usage: ' . round(memory_get_usage() / 1048576, 2) . "M\n";
@criss721
Copy link

criss721 commented Oct 7, 2023

thank you for your code it really helped me @};-
I had some issues with PDF so just changed the cipher from 'aes-256-cbc' to 'idea-cbc' and increased FILE_ENCRYPTION_BLOCKS to 1000000
everything works perfectly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment