Created
January 19, 2022 02:33
-
-
Save donaldsteele/6bcd2159cbcfc26696c2ff7408b80a9e to your computer and use it in GitHub Desktop.
php aes 256 encryption example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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