Encryption and security are interesting subjects-- both far beyond the scope of any forum post I could ever write. There are lots of different ways to go about keeping hackers out of the web application you're developing. Some of these become standard (md5 is a function in most builds of PHP) while others require a bit more knowledge (e.g. using hash("sha256", $password) instead of sha1($password) for password hashes).
Often times, implementing security carries the risk of making code messy and unreadable. As a result, I often refactor code I had written for security purposes into functions in my own special library. Here's a small selection of some of the more versatile functions.
All of these functions have been tested with PHP 5.2.17 and 5.3.5; although most of these should work on earlier versions.
AES-256 and TwoFish shorthand functions for plaintext encryption (requires mcrypt):
PHP Code:
function AES256_Encrypt($sValue, $sSecretKey)
{
return trim(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
function AES256_Decrypt($sValue, $sSecretKey)
{
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
function TwoFish_Encrypt($sValue, $sSecretKey) {
return trim(base64_encode(mcrypt_encrypt(MCRYPT_TWOFISH, $sSecretKey, $sValue, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TWOFISH, MCRYPT_MODE_ECB), MCRYPT_RAND))));
}
function TwoFish_Decrypt($sValue, $sSecretKey) {
return trim(mcrypt_decrypt(MCRYPT_TWOFISH, $sSecretKey, base64_decode($sValue), MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_TWOFISH, MCRYPT_MODE_ECB), MCRYPT_RAND)));
}
NoInject: For stopping SQL injections the lazy way.
PHP Code:
function noinject($query, $mode="mysql") {
if(get_magic_quotes_runtime()) $query = stripslashes($query);
if($mode == "sqlite") {
return sqlite_escape_string($query);
} else {
return mysql_real_escape_string($query);
}
}
Force ASCII -- Just a shorthand for stripping non-ASCII characters in case your specific application uses non-ASCII characters for delimiting data (for example):
PHP Code:
function forceASCII($in) {
return preg_replace('/[^(\x20-\x7F)]*/','', $in);
}
Whether you're new to PHP or a refined coder, you should find use for these functions if you don't already have your own.