Created
February 9, 2014 23:10
-
-
Save alexchung/8907533 to your computer and use it in GitHub Desktop.
Blockout encryption/decryption methods in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Blockout { | |
public static function enblockout($s, $key) { | |
// user provided blockout encoder | |
return; | |
} | |
public static function deblockout($blockout, $key) { | |
// user provided blockout decoder | |
return; | |
} | |
public static function hash($s) { | |
// generate a random salt | |
$salt = bin2Hex(openssl_random_pseudo_bytes(22)); | |
// bcrypt for password hashing with complexity of 12: http://php.net/crypt | |
$hashed = crypt($s, '$2a$12$' . $salt); | |
return $hashed; | |
} | |
public static function hashVerify($s, $hashed) { | |
return crypt($s, $hashed) === $hashed; | |
} | |
public static function hashToAES256Key($hash) { | |
// return binary NOT hex version of hash | |
return hash('sha256', $hash, true); | |
} | |
public static function encrypt($s, $key) { | |
// create the random iv | |
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND); | |
// AES encrypt | |
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $s, MCRYPT_MODE_CBC, $iv); | |
// return the encrypted and iv | |
$data['encrypted'] = trim(base64_encode($encrypted)); | |
$data['iv'] = base64_encode($iv); | |
return $data; | |
} | |
public static function decrypt($s, $key, $iv) { | |
// base64 decode s | |
$s = base64_decode($s); | |
// base64 decode the iv | |
$iv = base64_decode($iv); | |
// AES decrypt | |
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $s, MCRYPT_MODE_CBC, $iv); | |
// return depaded decrypted | |
return trim($decrypted); | |
} | |
public static function main($argc, $argv) { | |
// test hash/verify hash | |
$hash = Blockout::hash("password"); | |
print "hash: $hash\n"; | |
$isVerified = Blockout::hashVerify("password", $hash); | |
print "isVerified: " . (($isVerified) ? "TRUE" : "FALSE") . "\n"; | |
// test encrypt/decrypt | |
$encrypted = Blockout::encrypt("hello", "password"); | |
print "encrypted: " . $encrypted['encrypted'] . "\n"; | |
print "iv: " . $encrypted['iv'] . "\n"; | |
$decrypted = Blockout::decrypt($encrypted['encrypted'], "password", $encrypted['iv']); | |
print "decrypted: " . $decrypted . "\n"; | |
} | |
} | |
// execute main | |
Blockout::main($_SERVER['argc'], $_SERVER['argv']); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment