phpseclib: Symmetric Key Encryption Examples and Notes

Cipher:

Encryption Mode:

Key Length:

Key Derivation:

<?php
include('Crypt/AES.php');
include('Crypt/Random.php');

$cipher = new Crypt_AES(
);
 // could use CRYPT_AES_MODE_CBC
// keys are null-padded to the closest valid size
// longer than the longest key and it's truncated
//$cipher->setKeyLength(128);
$cipher->setKey('abcdefghijklmnop');
// the IV defaults to all-NULLs if not explicitly defined
$cipher->setIV(crypt_random_string($cipher->getBlockLength() >> 3));

$size = 10 * 1024;
$plaintext = str_repeat('a', $size);

echo $cipher->decrypt($cipher->encrypt($plaintext));
?>

Speed Comparisons

phpseclib uses OpenSSL or mcrypt (in that order) if they're available and a pure-PHP implementation when it is not. Neither OpenSSL or mcrypt can be beaten in terms of speed by a pure-PHP implementation, however, as the following demonstrates, even phpseclib's pure-PHP implementation is surprisingly fast.

The following table compares the speed of five different pure-PHP implementations of AES when ran on 1MB of text on an Intel Core i5-3320M CPU @ 2.6GHz with PHP 5.5.3. The numbers listed are averaged from two different trials and are measured in seconds. phpseclib's implementation is highlighted. All implementations can be viewed by clicking on their names and the table was generated with benchmark.phps.

Implementation Speed
movable-type.phps 21.164710998535
phpaes.phps 37.811162352562
phpclasses1.phps 17.648010134697
phpclasses2.phps 43.407482504844
phpseclib.phps 1.0410599708557

As can be seen, phpseclib's implementations are the fastest. Note that if mcrypt and OpenSSL weren't explicitily disabled phpseclib would have been even faster.