AES PHP Implementation

= 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));
?>