Difference between revisions of "AES PHP Implementation"

From Second Life Wiki
Jump to navigation Jump to search
m (language tags to <source>)
 
(12 intermediate revisions by 2 users not shown)
Line 1: Line 1:
= Description =
= Description =
The following is a port of the [[AES LSL Implementation|LSL AES Engine]] by [[Haravikk Mistral]], allowing you to process Java and LSL compatible AES messages in PHP.
The following is a PHP class compatible with the [[AES LSL Implementation|LSL AES Engine]] by [[Haravikk Mistral]], allowing you to process Java and LSL compatible AES messages in PHP.


The Crypto class provided performs extremely well on most PHP set-ups, but the cost of including the file can vary with a number of factors. For this reason if you are only using AES encryption within a single script, you may consider entering the Crypto class directly into this script, rather than including it.
The Crypto class provided performs extremely well on most PHP set-ups, but the cost of including the file can vary with a number of factors. For this reason if you are only using AES encryption within a single script, you may consider entering the Crypto class directly into this script, rather than including it.
Line 6: Line 6:
'''NOTE''': The PHP implementation includes helper functions for handling strings, which are used in the examples, as the <code>base64_decode()</code> function provided by PHP will attempt to process null-characters produced as a result of the 6-bit to 8-bit conversion process. If you wish to process strings with null-characters at the end, then you will need to use <code>invertPadBase64CipherToString()</code> and call base64_decode yourself on the result.
'''NOTE''': The PHP implementation includes helper functions for handling strings, which are used in the examples, as the <code>base64_decode()</code> function provided by PHP will attempt to process null-characters produced as a result of the 6-bit to 8-bit conversion process. If you wish to process strings with null-characters at the end, then you will need to use <code>invertPadBase64CipherToString()</code> and call base64_decode yourself on the result.


= Class (using mcrypt)=
= Implementations =
<php><?php
== mcrypt ==
define('AES_MODE_CBC', 1);
The following is the preferred PHP class but requires a PHP installation with the mcrypt module. It supports CBC and CFB modes, and the custom wrapper class implements all padding modes supported by the LSL implementation.
define('AES_MODE_CFB', 2);


define('AES_PAD_NONE', 128);
<source lang="php"><?php
define('AES_PAD_RBT', 129);
define('AES_MODE_CBC', 1);
define('AES_PAD_NULLS', 130);
define('AES_MODE_CFB', 2);
 
define('AES_PAD_NONE', 128);
define('AES_PAD_RBT', 129);
define('AES_PAD_NULLS', 130);
define('AES_PAD_NULLS_SAFE', 131);
define('AES_PAD_NULLS_SAFE', 131);
define('AES_PAD_ZEROES', 132);
define('AES_PAD_ZEROES', 132);
define('AES_PAD_RANDOM', 133);
define('AES_PAD_RANDOM', 133);


define('AES_DEFAULT_PAD', 512);
define('AES_DEFAULT_PAD', 512);


class Crypto {
class Crypto {
Line 70: Line 73:


public function padStringCipherToBase64(&$cipher) {
public function padStringCipherToBase64(&$cipher) {
return self::binaryToBase64($this->padCipher($cipher));
}
public function invertPadBase64CipherToString(&$cipher) {
return $this->invertPadCipher(self::base64ToBinary($cipher));
}
public function padBase64CipherToHex(&$cipher) {
return self::binaryToHex(
$this->padCipher(self::base64ToBinary($cipher)));
}
public function padBase64CipherToBase64(&$cipher) {
return self::binaryToBase64(
return self::binaryToBase64(
$this->padCipher(
$this->padCipher(self::base64ToBinary($cipher)));
self::base64ToBinary(base64_encode($cipher))));
}
}


public function invertPadBase64CipherToString(&$cipher) {
private function padCipher(&$data) {
$s = self::binaryToBase64(
$padding = $this->padType;
$this->invertPadCipher(self::base64ToBinary($cipher)));
if ($padding == AES_PAD_NONE) {
if ($this->mode == AES_MODE_CFB)
return $this->cipher($data);
$padding = AES_PAD_RBT;
}
 
$blockSize = $this->padSize;
if ($padding == AES_PAD_RBT) $blockSize = 128;
 
$bytes  = mb_strlen($data, '8bit');
$bits = $bytes << 3;
$blocks = (integer)($bits / $blockSize);
$extra  = $bits % $blockSize;
 
if ($padding == AES_PAD_RBT) {
if ($extra > 0) {
$ebytes = $extra >> 3;
if (($ebytes << 3) < $extra) ++$ebytes;
 
$pos = $bytes - $ebytes;
$t = mb_substr($data, $pos, $ebytes, '8bit');
if ($blocks < 1) {
$data = '';
$lb = $this->cipher($this->cipher($iv));
} else {
$data = $this->cipher(
mb_substr($data, 0, $pos, '8bit')
);
 
$lb = $this->cipher(
mb_substr($data, $pos - 16, 16, '8bit')
);
}
 
for ($i = 0; $i < $ebytes; ++$i)
$data .= $t{$i} ^ $lb{$i};
 
return $data;
}
 
return $this->cipher($data);
} else {
$extra = $blockSize - $extra;
 
if ($padding == AES_PAD_NULLS_SAFE) {
++$bits;
$data .= "\x80";
 
if ((--$extra) < 0) $extra += $blockSize;
$padding = AES_PAD_NULLS;
}
 
$ebytes = $extra >> 3;
if ($ebytes <= 0) {
if ($padding == AES_PAD_NULLS)
return $this->cipher($data);
 
$ebytes = $blockSize >> 3;
$extra += $blockSize;
}
 
$bits += $extra;
 
if ($ebytes > 0) {
$final = -1;
if ($padding != AES_PAD_NULLS)
$final = $ebytes - 1;
 
$byte = 0;
for ($i = 0; $i < $ebytes; ++$i) {
if (($padding != AES_PAD_NULLS) &&
($i == $final))
$byte = $ebytes;
else if ($padding == AES_PAD_RANDOM)
$byte = mt_rand(0, 255);
$data .= pack('C', $byte);
}
}
 
return $this->cipher($data);
}
}
 
public function invertPadHexCipherToHex(&$cipher) {
return self::binaryToHex($this->invertPadCipher(self::hexToBinary($cipher)));
}
 
public function invertPadHexCipherToBase64(&$cipher) {
return self::binaryToBase64($this->invertPadCipher(self::hexToBinary($cipher)));
}
 
public function invertPadBase64CipherToHex(&$cipher) {
return self::binaryToHex($this->invertPadCipher(self::base64ToBinary($cipher)));
}
 
public function invertPadBase64CipherToBase64(&$cipher) {
return self::binaryToBase64($this->invertPadCipher(self::base64ToBinary($cipher)));
}
 
private function invertPadCipher(&$data) {
$padding = $this->padType;
if ($padding == AES_PAD_NONE) {
if ($this->mode == AES_MODE_CFB)
return $this->invertCipher($data);
$padding = AES_PAD_RBT;
}
 
$blockSize = $this->padSize;
if ($padding == AES_PAD_RBT) $blockSize = 128;
$bytes  = mb_strlen($data, '8bit');
$bits = $bytes << 3;
$blocks = (integer)($bits / $blockSize);
$extra  = $bits % $blockSize;
 
if ($padding == AES_PAD_RBT) {
if ($extra > 0) {
$ebytes = $extra >> 3;
if (($ebytes << 3) < $extra) ++$ebytes;
 
$pos = $bytes - $ebytes;
$t = mb_substr($data, $pos, $ebytes, '8bit');
 
if ($blocks < 1)
$lb = $this->cipher(
$this->cipher($this->iv)
);
else {
$start = $bytes - (16 + $ebytes);
$lb = $this->cipher(
mb_substr($data, $start, 16, '8bit')
);
 
$data = $this->invertCipher(
mb_substr($data, 0, $pos, '8bit')
);
}
 
for ($i = 0; $i < $ebytes; ++$i)
$data .= $t{$i} ^ $lb{$i};
return $data;
}
return $this->invertCipher($data);
} else {
if ($extra > 0) {
$bits -= $extra;
 
$ebytes = $extra >> 3;
if (($e << 3) < $extra) ++$ebytes;
$extra = $ebytes;


if ($this->padType != AES_PAD_NULLS_SAFE) {
if ($extra <= 0) $extra = 1;
// Trim null-characters (A's), since php's base64
// functions don't trim them like they should.
$count = count($data);
$l = $o = mb_strlen($s);
if ($extra > $bytes) return "\0";
while (($l) >= 0) {
$c = mb_substr($s, $l - 1, 1);
$e = ($c == '=');
if ($e) --$o; // ignore pad characters


if (($c != 'A') && !$e) break;
$data = mb_substr($data, 0, $bytes - $extra, '8bit');
--$l;
}
}


if ($l != $o) {
$data = $this->invertCipher($data);
$s = mb_substr($s, 0, $l);
 
$ebytes = 0; $excessBits = 0;
 
if (($padding == AES_PAD_NULLS) ||
    ($padding == AES_PAD_NULLS_SAFE)) {
$v = 0; $continue = true;


$l %= 4;
while ($byte = ($data{$index = ($bytes - ($ebytes + 1))}) == "\0")
if ($l) {
++$ebytes;
if ($l == 2) $s .= '==';
 
else if ($l == 1) $s .= '=';
if ($padding == AES_PAD_NULLS_SAFE) {
$i = 1;
while ($i < 0xFF) {
++$excessBits;
if ($byte & $i) {
$byte ^= $i;
break;
}
$i <<= 1;
}
$data{$index} = $byte;
}
}
} else {
$ebytes = $data{$bytes - 1} & 0xFF;
if (($ebytes << 3) >= $bits) return "\0";
}
}
if ($ebytes > 0)
$data = mb_substr($data, 0, $bytes - $ebytes);
$bits -= ($ebytes << 3) + $excessBits;
return $data;
}
}
}
private function invertCipher($data) {
if ($data == "") return "";
mcrypt_generic_init($this->module, $this->key, $this->iv);
$decrypted = mdecrypt_generic($this->module, $data);
mcrypt_generic_deinit($this->module);
return $decrypted;
}


return base64_decode($s);
private function cipher($data) {
if ($data == "") return "";
mcrypt_generic_init($this->module, $this->key, $this->iv);
$cipherText = mcrypt_generic($this->module, $data);
mcrypt_generic_deinit($this->module);
return $cipherText;
}
 
private static function base64ToBinary(&$base64Data) {
return base64_decode($base64Data);
}
 
private static function hexToBinary(&$hexData) {
return pack('H*', $hexData);
}
 
private static function binaryToBase64(&$binary) {
return base64_encode($binary);
}
 
private static function binaryToHex(&$binary) {
$unpacked = unpack('H*hexchars', $binary);
return '0x'.implode('', $unpacked['hexchars']);
}
}
 
?></source>
 
== phpseclib ==
The following class follows the same structure as the one above and implements the same padding schemes, but provides an alternative implementation using [http://phpseclib.sourceforge.net/ phpseclib]. This implementation only supports CBC (the currently recommended mode of operation), but phpseclib has the advantage that it can be installed on hosts that do not have mcrypt (though it will support mcrypt when it is available), so it allows you to produce more portable code.
 
Thanks to [[User:John Avium|John Avium]] for recommending the use of this library.
 
<source lang="php"><?php
include_once 'phpseclib/Crypt/AES.php';
 
define('AES_MODE_CBC', 1);
 
define('AES_PAD_NONE', 128);
define('AES_PAD_RBT', 129);
define('AES_PAD_NULLS', 130);
define('AES_PAD_NULLS_SAFE', 131);
define('AES_PAD_ZEROES', 132);
define('AES_PAD_RANDOM', 133);
 
define('AES_DEFAULT_PAD', 512);
 
class Crypto {
private $mode = AES_MODE_CBC;
private $padType = AES_PAD_RBT;
private $padSize = AES_DEFAULT_PAD;
 
private $iv;
private $key;
private $changed = true;
private $module;
 
public function Crypto($mode=0, $padType=0, $padSize=0) {
if ($padSize >= 128) $this->padSize = $padSize;
if (($padType >= 128) && ($padType <= 133))
$this->padType = $padType;
 
// Re-add this if phpseclib ever adds more modes of operation
//if (($mode >= 1) || ($mode <= 2)) $this->mode = $mode;
$this->module = new Crypt_AES(CRYPT_AES_MODE_CBC);
$this->module->disablePadding();
}
 
public function setHexKey(&$key) {
$this->key = self::hexToBinary($key);
$this->changed = true;
}
 
public function setBase64Key(&$key) {
$this->key = self::base64ToBinary($key);
$this->changed = true;
}
 
public function setHexIV(&$iv) {
$this->iv = self::hexToBinary($iv);
$this->changed = true;
}
 
public function padHexCipherToHex(&$cipher) {
return self::binaryToHex(
$this->padCipher(self::hexToBinary($cipher)));
}
 
public function padHexCipherToBase64(&$cipher) {
return self::binaryToBase64(
$this->padCipher(self::hexToBinary($cipher)));
}
public function padStringCipherToBase64(&$cipher) {
return self::binaryToBase64($this->padCipher($cipher));
}
 
public function invertPadBase64CipherToString(&$cipher) {
return $this->invertPadCipher(self::base64ToBinary($cipher));
}
}


Line 320: Line 618:
if ($data == "") return "";
if ($data == "") return "";
mcrypt_generic_init($this->module, $this->key, $this->iv);
if ($this->changed) {
$decrypted = mdecrypt_generic($this->module, $data);
$this->module->setKey($this->key);
mcrypt_generic_deinit($this->module);
$this->module->setIV($this->iv);
return $decrypted;
}
 
return $this->module->decrypt($data);
}
}


Line 329: Line 629:
if ($data == "") return "";
if ($data == "") return "";
mcrypt_generic_init($this->module, $this->key, $this->iv);
if ($this->changed) {
$cipherText = mcrypt_generic($this->module, $data);
$this->module->setKey($this->key);
mcrypt_generic_deinit($this->module);
$this->module->setIV($this->iv);
return $cipherText;
}
return $this->module->encrypt($data);
}
}


Line 351: Line 653:
return '0x'.implode('', $unpacked['hexchars']);
return '0x'.implode('', $unpacked['hexchars']);
}
}
}</php>
}
?></source>


= Examples =
= Examples =
The following are simple examples, and do not demonstrate real-world usage. They do not handle reading the message from Second Life, of which note, you will need to remember that PHP replaces any '+' characters (part of the base64 character-set) with spaces, unless you first replace them using URI encoding in your LSL script. The easiest solution is to use <code>str_replace($base64data, ' ', '+')</code> assuming your data contains only base64 encoded characters.
The following are simple examples, and do not demonstrate real-world usage. They do not handle reading the message from Second Life, of which note, you will need to remember that PHP replaces any '+' characters (part of the base64 character-set) with spaces, unless you first replace them using URI encoding in your LSL script. The easiest solution is to use <code>str_replace(' ', '+', $base64data)</code> assuming your data contains only base64 encoded characters.


Importantly the examples below do not handle input-validation, or key-generation, which are both critical to maintaining security. It is up to the developer to determine how they wish to verify the identify of their in-world objects from malicious attackers, and how they will generate a key, and keep it updated.
Importantly the examples below do not handle input-validation, or key-generation, which are both critical to maintaining security. It is up to the developer to determine how they wish to verify the identify of their in-world objects from malicious attackers, and how they will generate a key, and keep it updated.


== Encryption ==
== Encryption ==
<php><?php
<source lang="php"><?php
include 'aes.php';
include 'aes.php';


Line 366: Line 670:
$myMsg = 'Hello world! I am a lovely message waiting to be encrypted!';
$myMsg = 'Hello world! I am a lovely message waiting to be encrypted!';


$aes = new Crypto(AES_MODE_CFB, AES_PAD_NONE, 512);
$aes = new Crypto(AES_MODE_CBC, AES_PAD_NULLS_SAFE, 512);
$aes->setHexKey($myKey);
$aes->setHexKey($myKey);
$aes->setHexIV ($myIV);
$aes->setHexIV ($myIV);


die ($aes->padStringCipherToBase64($myMsg));
die ($aes->padStringCipherToBase64($myMsg));
?></php>
?></source>


== Decryption ==
== Decryption ==
<php><?php
<source lang="php"><?php
include 'aes.php';
include 'aes.php';


$myKey = '1234567890ABCDEF0123456789ABCDEF';
$myKey = '1234567890ABCDEF0123456789ABCDEF';
$myIV  = '89ABCDEF0123456789ABCDEF01234567';
$myIV  = '89ABCDEF0123456789ABCDEF01234567';
$myMsg = 'Mdn6jGTwRPMOKTYTTdDKGm9KScz26LIz96KVOGAeMw3hpwByPfa07PDRHxRW4TIh5dmu5LlhKpTQChi=';
$myMsg = 'slihkO6t9I/yfvfUpI0Rthagd/z8j1s5qh/PSbKGBg4N3PoQgUFdcCVnqOYku53csPmhn7i+XeHM9lsOO47exg==';


$aes = new Crypto(AES_MODE_CFB, AES_PAD_NONE, 512);
$aes = new Crypto(AES_MODE_CBC, AES_PAD_NULLS_SAFE, 512);
$aes->setHexKey($myKey);
$aes->setHexKey($myKey);
$aes->setHexIV ($myIV);
$aes->setHexIV ($myIV);


die ($aes-> invertPadBase64CipherToString($myMsg));
die ($aes-> invertPadBase64CipherToString($myMsg));
?></php>
?></source>

Latest revision as of 11:16, 25 January 2015

Description

The following is a PHP class compatible with the LSL AES Engine by Haravikk Mistral, allowing you to process Java and LSL compatible AES messages in PHP.

The Crypto class provided performs extremely well on most PHP set-ups, but the cost of including the file can vary with a number of factors. For this reason if you are only using AES encryption within a single script, you may consider entering the Crypto class directly into this script, rather than including it.

NOTE: The PHP implementation includes helper functions for handling strings, which are used in the examples, as the base64_decode() function provided by PHP will attempt to process null-characters produced as a result of the 6-bit to 8-bit conversion process. If you wish to process strings with null-characters at the end, then you will need to use invertPadBase64CipherToString() and call base64_decode yourself on the result.

Implementations

mcrypt

The following is the preferred PHP class but requires a PHP installation with the mcrypt module. It supports CBC and CFB modes, and the custom wrapper class implements all padding modes supported by the LSL implementation.

<?php
define('AES_MODE_CBC', 		1);
define('AES_MODE_CFB', 		2);

define('AES_PAD_NONE', 		128);
define('AES_PAD_RBT', 		129);
define('AES_PAD_NULLS', 	130);
define('AES_PAD_NULLS_SAFE',	131);
define('AES_PAD_ZEROES', 	132);
define('AES_PAD_RANDOM', 	133);

define('AES_DEFAULT_PAD',	512);

class Crypto {
	private $mode		= AES_MODE_CBC;
	private $padType	= AES_PAD_RBT;
	private $padSize	= AES_DEFAULT_PAD;

	private $iv;
	private $key;
	
	private $module;

	public function Crypto($mode=0, $padType=0, $padSize=0) {
		if ($padSize >= 128) $this->padSize = $padSize;
		if (($padType >= 128) && ($padType <= 133)) 
			$this->padType = $padType;

		if (($mode >= 1) || ($mode <= 2)) $this->mode = $mode;
		
		$mcryptMode = 'cbc';
		if ($this->mode == AES_MODE_CFB) $mcryptMode = 'ncfb';
		
		$this->module = mcrypt_module_open('rijndael-128', '', $mcryptMode, '');
	}
	
	public function __destruct() {
		mcrypt_module_close($this->module);
	}

	public function setHexKey(&$key) {
		$this->key = self::hexToBinary($key);
	}

	public function setBase64Key(&$key) {
		$this->key = self::base64ToBinary($key);
	}

	public function setHexIV(&$iv) {
		$this->iv = self::hexToBinary($iv);
	}

	public function padHexCipherToHex(&$cipher) {
		return self::binaryToHex(
			$this->padCipher(self::hexToBinary($cipher)));
	}

	public function padHexCipherToBase64(&$cipher) {
		return self::binaryToBase64(
			$this->padCipher(self::hexToBinary($cipher)));
	}

	public function padStringCipherToBase64(&$cipher) {
		return self::binaryToBase64($this->padCipher($cipher));
	}

	public function invertPadBase64CipherToString(&$cipher) {
		return $this->invertPadCipher(self::base64ToBinary($cipher));
	}

	public function padBase64CipherToHex(&$cipher) {
		return self::binaryToHex(
			$this->padCipher(self::base64ToBinary($cipher)));
	}

	public function padBase64CipherToBase64(&$cipher) {
		return self::binaryToBase64(
			$this->padCipher(self::base64ToBinary($cipher)));
	}

	private function padCipher(&$data) {
		$padding = $this->padType;
		if ($padding == AES_PAD_NONE) {
			if ($this->mode == AES_MODE_CFB) 
				return $this->cipher($data);
			$padding = AES_PAD_RBT;
		}

		$blockSize = $this->padSize;
		if ($padding == AES_PAD_RBT) $blockSize = 128;

		$bytes  = mb_strlen($data, '8bit');
		$bits	= $bytes << 3;
		$blocks = (integer)($bits / $blockSize);
		$extra  = $bits % $blockSize;

		if ($padding == AES_PAD_RBT) {
			if ($extra > 0) {
				$ebytes = $extra >> 3;
				if (($ebytes << 3) < $extra) ++$ebytes;

				$pos = $bytes - $ebytes;
				$t = mb_substr($data, $pos, $ebytes, '8bit');
				
				if ($blocks < 1) {
					$data = '';
					$lb = $this->cipher($this->cipher($iv));
				} else {
					$data = $this->cipher(
						mb_substr($data, 0, $pos, '8bit')
					);

					$lb = $this->cipher(
						mb_substr($data, $pos - 16, 16, '8bit')
					);
				}

				for ($i = 0; $i < $ebytes; ++$i) 
					$data .= $t{$i} ^ $lb{$i};

				return $data;
			}

			return $this->cipher($data);
		} else {
			$extra = $blockSize - $extra;

			if ($padding == AES_PAD_NULLS_SAFE) {
				++$bits;
				$data .= "\x80";

				if ((--$extra) < 0) $extra += $blockSize;
				$padding = AES_PAD_NULLS;
			}

			$ebytes = $extra >> 3;
			if ($ebytes <= 0) {
				if ($padding == AES_PAD_NULLS) 
					return $this->cipher($data);

				$ebytes = $blockSize >> 3;
				$extra += $blockSize;
			}

			$bits += $extra;

			if ($ebytes > 0) {
				$final = -1;
				if ($padding != AES_PAD_NULLS) 
					$final = $ebytes - 1;

				$byte = 0;
				for ($i = 0; $i < $ebytes; ++$i) {
					if (($padding != AES_PAD_NULLS) && 
						($i == $final)) 
						$byte = $ebytes;
					else if ($padding == AES_PAD_RANDOM) 
						$byte = mt_rand(0, 255);
					$data .= pack('C', $byte);
				}
			}

			return $this->cipher($data);
		}
	}

	public function invertPadHexCipherToHex(&$cipher) {
		return self::binaryToHex($this->invertPadCipher(self::hexToBinary($cipher)));
	}

	public function invertPadHexCipherToBase64(&$cipher) {
		return self::binaryToBase64($this->invertPadCipher(self::hexToBinary($cipher)));
	}

	public function invertPadBase64CipherToHex(&$cipher) {
		return self::binaryToHex($this->invertPadCipher(self::base64ToBinary($cipher)));
	}

	public function invertPadBase64CipherToBase64(&$cipher) {
		return self::binaryToBase64($this->invertPadCipher(self::base64ToBinary($cipher)));
	}

	private function invertPadCipher(&$data) {
		$padding = $this->padType;
		if ($padding == AES_PAD_NONE) {
			if ($this->mode == AES_MODE_CFB) 
				return $this->invertCipher($data);
			$padding = AES_PAD_RBT;
		}

		$blockSize = $this->padSize;
		if ($padding == AES_PAD_RBT) $blockSize = 128;
		
		$bytes  = mb_strlen($data, '8bit');
		$bits	= $bytes << 3;
		$blocks = (integer)($bits / $blockSize);
		$extra  = $bits % $blockSize;

		if ($padding == AES_PAD_RBT) {
			if ($extra > 0) {
				$ebytes = $extra >> 3;
				if (($ebytes << 3) < $extra) ++$ebytes;

				$pos = $bytes - $ebytes;
				$t = mb_substr($data, $pos, $ebytes, '8bit');

				if ($blocks < 1) 
					$lb = $this->cipher(
						$this->cipher($this->iv)
					);
				else {
					$start = $bytes - (16 + $ebytes);
					$lb = $this->cipher(
						mb_substr($data, $start, 16, '8bit')
					);

					$data = $this->invertCipher(
						mb_substr($data, 0, $pos, '8bit')
					);
				}

				for ($i = 0; $i < $ebytes; ++$i) 
					$data .= $t{$i} ^ $lb{$i};
					
				return $data;
			}
			
			return $this->invertCipher($data);
		} else {
			if ($extra > 0) {
				$bits -= $extra;

				$ebytes = $extra >> 3;
				if (($e << 3) < $extra) ++$ebytes;
				$extra = $ebytes;

				if ($extra <= 0) $extra = 1;
 
				$count = count($data);
				if ($extra > $bytes) return "\0";

				$data = mb_substr($data, 0, $bytes - $extra, '8bit');
			}

			$data = $this->invertCipher($data);

			$ebytes = 0; $excessBits = 0;

			if (($padding == AES_PAD_NULLS) || 
			    ($padding == AES_PAD_NULLS_SAFE)) {
				$v = 0; $continue = true;

				while ($byte = ($data{$index = ($bytes - ($ebytes + 1))}) == "\0") 
					++$ebytes;

				if ($padding == AES_PAD_NULLS_SAFE) {
					$i = 1;
					while ($i < 0xFF) {
						++$excessBits;
						if ($byte & $i) {
							$byte ^= $i;
							break;
						}
						$i <<= 1;
					}
					$data{$index} = $byte;
				}
			} else {
				$ebytes = $data{$bytes - 1} & 0xFF;
				if (($ebytes << 3) >= $bits) return "\0";
			}

			if ($ebytes > 0) 
				$data = mb_substr($data, 0, $bytes - $ebytes);

			$bits -= ($ebytes << 3) + $excessBits;

			return $data;
		}
	}

	private function invertCipher($data) {
		if ($data == "") return "";
	
		mcrypt_generic_init($this->module, $this->key, $this->iv);
		$decrypted = mdecrypt_generic($this->module, $data);
		mcrypt_generic_deinit($this->module);
		return $decrypted;
	}

	private function cipher($data) {
		if ($data == "") return "";
		
		mcrypt_generic_init($this->module, $this->key, $this->iv);
		$cipherText = mcrypt_generic($this->module, $data);
		mcrypt_generic_deinit($this->module);
		return $cipherText;
	}

	private static function base64ToBinary(&$base64Data) {
		return base64_decode($base64Data);
	}

	private static function hexToBinary(&$hexData) {
		return pack('H*', $hexData);
	}

	private static function binaryToBase64(&$binary) {
		return base64_encode($binary);
	}

	private static function binaryToHex(&$binary) {
		$unpacked = unpack('H*hexchars', $binary);
		return '0x'.implode('', $unpacked['hexchars']);
	}
}

?>

phpseclib

The following class follows the same structure as the one above and implements the same padding schemes, but provides an alternative implementation using phpseclib. This implementation only supports CBC (the currently recommended mode of operation), but phpseclib has the advantage that it can be installed on hosts that do not have mcrypt (though it will support mcrypt when it is available), so it allows you to produce more portable code.

Thanks to John Avium for recommending the use of this library.

<?php
include_once 'phpseclib/Crypt/AES.php';

define('AES_MODE_CBC', 		1);

define('AES_PAD_NONE', 		128);
define('AES_PAD_RBT', 		129);
define('AES_PAD_NULLS', 	130);
define('AES_PAD_NULLS_SAFE',	131);
define('AES_PAD_ZEROES', 	132);
define('AES_PAD_RANDOM', 	133);

define('AES_DEFAULT_PAD',	512);

class Crypto {
	private $mode		= AES_MODE_CBC;
	private $padType	= AES_PAD_RBT;
	private $padSize	= AES_DEFAULT_PAD;

	private $iv;
	private $key;
	private $changed	= true;
	
	private $module;

	public function Crypto($mode=0, $padType=0, $padSize=0) {
		if ($padSize >= 128) $this->padSize = $padSize;
		if (($padType >= 128) && ($padType <= 133)) 
			$this->padType = $padType;

		// Re-add this if phpseclib ever adds more modes of operation
		//if (($mode >= 1) || ($mode <= 2)) $this->mode = $mode;
		
		$this->module = new Crypt_AES(CRYPT_AES_MODE_CBC);
		$this->module->disablePadding();
	}

	public function setHexKey(&$key) {
		$this->key = self::hexToBinary($key);
		$this->changed = true;
	}

	public function setBase64Key(&$key) {
		$this->key = self::base64ToBinary($key);
		$this->changed = true;
	}

	public function setHexIV(&$iv) {
		$this->iv = self::hexToBinary($iv);
		$this->changed = true;
	}

	public function padHexCipherToHex(&$cipher) {
		return self::binaryToHex(
			$this->padCipher(self::hexToBinary($cipher)));
	}

	public function padHexCipherToBase64(&$cipher) {
		return self::binaryToBase64(
			$this->padCipher(self::hexToBinary($cipher)));
	}
	
	public function padStringCipherToBase64(&$cipher) {
		return self::binaryToBase64($this->padCipher($cipher));
	}

	public function invertPadBase64CipherToString(&$cipher) {
		return $this->invertPadCipher(self::base64ToBinary($cipher));
	}

	public function padBase64CipherToHex(&$cipher) {
		return self::binaryToHex(
			$this->padCipher(self::base64ToBinary($cipher)));
	}

	public function padBase64CipherToBase64(&$cipher) {
		return self::binaryToBase64(
			$this->padCipher(self::base64ToBinary($cipher)));
	}

	private function padCipher(&$data) {
		$padding = $this->padType;
		if ($padding == AES_PAD_NONE) {
			if ($this->mode == AES_MODE_CFB) 
				return $this->cipher($data);
			$padding = AES_PAD_RBT;
		}

		$blockSize = $this->padSize;
		if ($padding == AES_PAD_RBT) $blockSize = 128;

		$bytes  = mb_strlen($data, '8bit');
		$bits	= $bytes << 3;
		$blocks = (integer)($bits / $blockSize);
		$extra  = $bits % $blockSize;

		if ($padding == AES_PAD_RBT) {
			if ($extra > 0) {
				$ebytes = $extra >> 3;
				if (($ebytes << 3) < $extra) ++$ebytes;

				$pos = $bytes - $ebytes;
				$t = mb_substr($data, $pos, $ebytes, '8bit');
				
				if ($blocks < 1) {
					$data = '';
					$lb = $this->cipher($this->cipher($iv));
				} else {
					$data = $this->cipher(
						mb_substr($data, 0, $pos, '8bit')
					);

					$lb = $this->cipher(
						mb_substr($data, $pos - 16, 16, '8bit')
					);
				}

				for ($i = 0; $i < $ebytes; ++$i) 
					$data .= $t{$i} ^ $lb{$i};

				return $data;
			}

			return $this->cipher($data);
		} else {
			$extra = $blockSize - $extra;

			if ($padding == AES_PAD_NULLS_SAFE) {
				++$bits;
				$data .= "\x80";

				if ((--$extra) < 0) $extra += $blockSize;
				$padding = AES_PAD_NULLS;
			}

			$ebytes = $extra >> 3;
			if ($ebytes <= 0) {
				if ($padding == AES_PAD_NULLS) 
					return $this->cipher($data);

				$ebytes = $blockSize >> 3;
				$extra += $blockSize;
			}

			$bits += $extra;

			if ($ebytes > 0) {
				$final = -1;
				if ($padding != AES_PAD_NULLS) 
					$final = $ebytes - 1;

				$byte = 0;
				for ($i = 0; $i < $ebytes; ++$i) {
					if (($padding != AES_PAD_NULLS) && 
						($i == $final)) 
						$byte = $ebytes;
					else if ($padding == AES_PAD_RANDOM) 
						$byte = mt_rand(0, 255);
					$data .= pack('C', $byte);
				}
			}

			return $this->cipher($data);
		}
	}

	public function invertPadHexCipherToHex(&$cipher) {
		return self::binaryToHex($this->invertPadCipher(self::hexToBinary($cipher)));
	}

	public function invertPadHexCipherToBase64(&$cipher) {
		return self::binaryToBase64($this->invertPadCipher(self::hexToBinary($cipher)));
	}

	public function invertPadBase64CipherToHex(&$cipher) {
		return self::binaryToHex($this->invertPadCipher(self::base64ToBinary($cipher)));
	}

	public function invertPadBase64CipherToBase64(&$cipher) {
		return self::binaryToBase64($this->invertPadCipher(self::base64ToBinary($cipher)));
	}

	private function invertPadCipher(&$data) {
		$padding = $this->padType;
		if ($padding == AES_PAD_NONE) {
			if ($this->mode == AES_MODE_CFB) 
				return $this->invertCipher($data);
			$padding = AES_PAD_RBT;
		}

		$blockSize = $this->padSize;
		if ($padding == AES_PAD_RBT) $blockSize = 128;
		
		$bytes  = mb_strlen($data, '8bit');
		$bits	= $bytes << 3;
		$blocks = (integer)($bits / $blockSize);
		$extra  = $bits % $blockSize;

		if ($padding == AES_PAD_RBT) {
			if ($extra > 0) {
				$ebytes = $extra >> 3;
				if (($ebytes << 3) < $extra) ++$ebytes;

				$pos = $bytes - $ebytes;
				$t = mb_substr($data, $pos, $ebytes, '8bit');

				if ($blocks < 1) 
					$lb = $this->cipher(
						$this->cipher($this->iv)
					);
				else {
					$start = $bytes - (16 + $ebytes);
					$lb = $this->cipher(
						mb_substr($data, $start, 16, '8bit')
					);

					$data = $this->invertCipher(
						mb_substr($data, 0, $pos, '8bit')
					);
				}

				for ($i = 0; $i < $ebytes; ++$i) 
					$data .= $t{$i} ^ $lb{$i};
					
				return $data;
			}
			
			return $this->invertCipher($data);
		} else {
			if ($extra > 0) {
				$bits -= $extra;

				$ebytes = $extra >> 3;
				if (($e << 3) < $extra) ++$ebytes;
				$extra = $ebytes;

				if ($extra <= 0) $extra = 1;
 
				$count = count($data);
				if ($extra > $bytes) return "\0";

				$data = mb_substr($data, 0, $bytes - $extra, '8bit');
			}

			$data = $this->invertCipher($data);

			$ebytes = 0; $excessBits = 0;

			if (($padding == AES_PAD_NULLS) || 
			    ($padding == AES_PAD_NULLS_SAFE)) {
				$v = 0; $continue = true;

				while ($byte = ($data{$index = ($bytes - ($ebytes + 1))}) == "\0") 
					++$ebytes;

				if ($padding == AES_PAD_NULLS_SAFE) {
					$i = 1;
					while ($i < 0xFF) {
						++$excessBits;
						if ($byte & $i) {
							$byte ^= $i;
							break;
						}
						$i <<= 1;
					}
					$data{$index} = $byte;
				}
			} else {
				$ebytes = $data{$bytes - 1} & 0xFF;
				if (($ebytes << 3) >= $bits) return "\0";
			}

			if ($ebytes > 0) 
				$data = mb_substr($data, 0, $bytes - $ebytes);

			$bits -= ($ebytes << 3) + $excessBits;

			return $data;
		}
	}

	private function invertCipher($data) {
		if ($data == "") return "";
	
		if ($this->changed) {
			$this->module->setKey($this->key);
			$this->module->setIV($this->iv);
		}

		return $this->module->decrypt($data);
	}

	private function cipher($data) {
		if ($data == "") return "";
		
		if ($this->changed) {
			$this->module->setKey($this->key);
			$this->module->setIV($this->iv);
		}
		
		return $this->module->encrypt($data);
	}

	private static function base64ToBinary(&$base64Data) {
		return base64_decode($base64Data);
	}

	private static function hexToBinary(&$hexData) {
		return pack('H*', $hexData);
	}

	private static function binaryToBase64(&$binary) {
		return base64_encode($binary);
	}

	private static function binaryToHex(&$binary) {
		$unpacked = unpack('H*hexchars', $binary);
		return '0x'.implode('', $unpacked['hexchars']);
	}
}
 
?>

Examples

The following are simple examples, and do not demonstrate real-world usage. They do not handle reading the message from Second Life, of which note, you will need to remember that PHP replaces any '+' characters (part of the base64 character-set) with spaces, unless you first replace them using URI encoding in your LSL script. The easiest solution is to use str_replace(' ', '+', $base64data) assuming your data contains only base64 encoded characters.

Importantly the examples below do not handle input-validation, or key-generation, which are both critical to maintaining security. It is up to the developer to determine how they wish to verify the identify of their in-world objects from malicious attackers, and how they will generate a key, and keep it updated.

Encryption

<?php
include 'aes.php';

$myKey = '1234567890ABCDEF0123456789ABCDEF';
$myIV  = '89ABCDEF0123456789ABCDEF01234567';
$myMsg = 'Hello world! I am a lovely message waiting to be encrypted!';

$aes = new Crypto(AES_MODE_CBC, AES_PAD_NULLS_SAFE, 512);
$aes->setHexKey($myKey);
$aes->setHexIV ($myIV);

die ($aes->padStringCipherToBase64($myMsg));
?>

Decryption

<?php
include 'aes.php';

$myKey = '1234567890ABCDEF0123456789ABCDEF';
$myIV  = '89ABCDEF0123456789ABCDEF01234567';
$myMsg = 'slihkO6t9I/yfvfUpI0Rthagd/z8j1s5qh/PSbKGBg4N3PoQgUFdcCVnqOYku53csPmhn7i+XeHM9lsOO47exg==';

$aes = new Crypto(AES_MODE_CBC, AES_PAD_NULLS_SAFE, 512);
$aes->setHexKey($myKey);
$aes->setHexIV ($myIV);

die ($aes-> invertPadBase64CipherToString($myMsg));
?>