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).


$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.


$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.