AES Encryption With PHP


Easy text and file encryption

I’ve put together and released a basic encryption / decryption class for PHP. It uses the mycrypt library to handle the AES encryption using the RIJNDAEL 128 algorithm.

You can find the source on github by clicking here.

Text encryption is easy, and can be accomplished with a user provided key and iv, or by creating random ones. Be sure to save the random ones somewhere, as neither are saved by default (the iv is not added to the ciphertext).

include('aes.php');

$crypt = new aes_encryption();

$crypt->key = $crypt->rand_key();
$crypt->iv = $crypt->rand_iv();

// or to provide a passphrase and your own iv, you could do something like the
// following, though there are certainly better ways, this works well enough
// for testing purposes. 

// $passphrase = 'ThisIsMyPassphrase';
// $iv = substr(md5('YourIV'.$passphrase, true), 0, 16);
// $key = md5($passphrase, true);

// You would pass the below when initializing the class like:
// $crypt = new aes_encryption($key, $iv);

// we base64_encode() the plain text before encryption to ensure that the
// plaintext length's byte size is a multiple of 16.
$encrypted_string = $crypt->encrypt(base64_encode('this is a test'));
echo $encrypted_string.'<br>';

$decrypted_string = base64_decode($crypt->decrypt($encrypted_string));
echo $decrypted_string.'<br>';

File encryption is similarly easy. This method encrypts files in chunks of 4096 bytes to allow php to process large files without needing to load the entire file into memory at once.

include('aes.php');

$crypt = new aes_encryption();

$crypt->key = $crypt->rand_key();
$crypt->iv = $crypt->rand_iv();

$file = 'path/to/file/file.txt';

$crypt->encrypt_file($file, $file.'.enc');

$crypt->decrypt_file($file.'.enc', $file);

Checkout the github repo linked above to report bugs and to see the latest updates to the class.

  • Aulia Kharis Kurniawan

    i just trying to make upload file using auto encrypted with aes when upload, and auto decrypted when downlod from the server,and the key is password user who was logon, the idea is to secure the file in the server from un autorizide user.
    here i already success to make file upload to the server, but no auto encrypted file, so i want to use your code to make it work with the idea, but i just confused how to use your code in my project, could you help me?

    here my upload.php

    alert(‘successfully uploaded’);
    window.location.href=’home.php?success’;

    alert(‘gagal upload’);
    window.location.href=’home.php?fail’;

    `