使用 mcrypt 加/解密
Code: [Copy to clipboard]
function make_seed() {
list($usec, $sec) = explode(' ', microtime());
return(float) $sec +((float) $usec * 100000);
}
srand(make_seed());
/* 开启加密算法/ */
$td = mcrypt_module_open('twofish', '', 'ecb', '');
/* 建立 IV,并检测 key 的长度 */
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
/* 生成 key */
$key = substr(md5('very secret key'), 0, $ks);
/* 初始化加密程序 */
mcrypt_generic_init($td, $key, $iv);
/* 加密, $encrypted 保存的是已经加密后的数据 */
print $encrypted = mcrypt_generic($td, 'This is very important data');
/* 检测加密句柄 */
mcrypt_generic_deinit($td);
/* 初始化加密模块,用以解密 */
mcrypt_generic_init($td, $key, $iv);
/* 解密 */
$decrypted = mdecrypt_generic($td, $encrypted);
/* 检测解密句柄,并关闭模块 */
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
/* 显示原始字符串 */
echo trim($decrypted)."\n";
函数封装后的~
因为建立 IV 的时候,source 用了 MCRYPT_RAND
所以 srand();
Code: [Copy to clipboard]
<?php
function make_seed() {
list($usec, $sec) = explode(' ', microtime());
return(float) $sec +((float) $usec * 100000);
}
function twofish_encode($dat, $key)
{
srand(make_seed());
// Twofish 算法, ECB 模式
$td = mcrypt_module_open('twofish', '', 'ecb', '');
// If u use MCRYPT_RAND, make sure to invoke strand() first.
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
$gen_key = substr(md5($key), 0, $ks);
mcrypt_generic_init($td, $gen_key, $iv);
$encrypted = mcrypt_generic($td, $dat);
mcrypt_module_close($td);
return $encrypted;
}
function twofish_decode($dat, $key)
{
srand(make_seed());
// Twofish algorithm, ECB Mode
$td = mcrypt_module_open('twofish', '', 'ecb', '');
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$ks = mcrypt_enc_get_key_size($td);
$gen_key = substr(md5($key), 0, $ks);
mcrypt_generic_init($td, $gen_key, $iv);
$decrypted = mdecrypt_generic($td, $dat);
// Clear all buffer needed by the encryption
// Close the module
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return trim($decrypted);
}
// Some examples
$raw = 'It is confidential data.';
$key = '1314521-7576798-5468181';
// 加密数据
print $encode_data = twofish_encode($raw, $key);
// 解密数据
print $decode_data = twofish_decode($encode_data, $key);
?>