[PHP]暗号化・複合化

暗号化・複合化

define('KEY', 'bsrNaTwou3PJJbUHMVp20BW0JFxszbOdTaYTtY2jD26TxNFZ');//getRandomStr(48)で取得
define('IV', 'rfKvr+rLztklJ0/6hc8ZmrILlMLVoan6ltu/SR2Bvzg=');//getCryptIV()で取得

$str='あいうえお';

$crypted_str = getEncrypt($str);
echo $crypted_str;
echo '<br/><br/>';
$decrypted_str = getDecrypt($crypted_str);
echo $decrypted_str;
exit;

function getEncrypt($data) {
    $resource = mcrypt_module_open('rijndael-256', '', 'ofb', '');
    $iv = base64_decode(str_rot13(IV));
    $ks = mcrypt_enc_get_key_size($resource);
    $key = substr(md5(KEY), 0, $ks);
    mcrypt_generic_init($resource, $key, $iv);
    $encrypt = mcrypt_generic($resource, $data);
    mcrypt_generic_deinit($resource);
    mcrypt_module_close($resource);
    return base64_encode($encrypt);
}
function getDecrypt($data) {
    $resource = mcrypt_module_open('rijndael-256', '', 'ofb', '');
    $iv = base64_decode(str_rot13(IV));
    $ks = mcrypt_enc_get_key_size($resource);
    $key = substr(md5(KEY), 0, $ks);
    mcrypt_generic_init($resource, $key, $iv);
    $decrypt = mdecrypt_generic($resource, base64_decode($data));
    mcrypt_generic_deinit($resource);
    mcrypt_module_close($resource);
    return $decrypt;
}
function getCryptIV(){
	$key = getRandomStr(48);
	$td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
	$iv  = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	$iv = base64_encode($iv);
	mcrypt_module_close($td);
	return $iv;
}
function getRandomStr($length=8){
	$str='';
	for ($i = 0, $str = null; $i < $length; ) {
		$num = mt_rand(0x30, 0x7A);
		if ((0x30 <= $num && $num <= 0x39) || (0x41 <= $num && $num <= 0x5A) || (0x61 <= $num && $num <= 0x7A)) {
			$str .= chr($num);
			$i++;
		}
	}
	return $str;
}