您的位置:首页 > 编程语言 > PHP开发

PHP使用DES进行加密和解密

2009-05-29 22:06 1011 查看
DES是一种标准的数据加密算法,关于这个算法的详细介绍可以参考wiki和百度百科:

wiki百科 百度百科

php中有一个扩展可以支持DES的加密算法,是:extension=php_mcrypt.dll

在配置文件中将这个扩展打开还不能够在windows环境下使用

需要将PHP文件夹下的 libmcrypt.dll 拷贝到系统的 system32 目录下,这是通过phpinfo可以查看到mcrypt表示这个模块可以正常试用了。

下面是PHP中使用DES加密解密的一个例子:

//$input - stuff to decrypt


//$key - the secret key to use




function do_mencrypt($input, $key)


{


$input = str_replace(""n", "", $input);


$input = str_replace(""t", "", $input);


$input = str_replace(""r", "", $input);


$key = substr(md5($key), 0, 24);


$td = mcrypt_module_open('tripledes', '', 'ecb', '');


$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);


mcrypt_generic_init($td, $key, $iv);


$encrypted_data = mcrypt_generic($td, $input);


mcrypt_generic_deinit($td);


mcrypt_module_close($td);


return trim(chop(base64_encode($encrypted_data)));


}




//$input - stuff to decrypt


//$key - the secret key to use




function do_mdecrypt($input, $key)


{


$input = str_replace(""n", "", $input);


$input = str_replace(""t", "", $input);


$input = str_replace(""r", "", $input);


$input = trim(chop(base64_decode($input)));


$td = mcrypt_module_open('tripledes', '', 'ecb', '');


$key = substr(md5($key), 0, 24);


$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);


mcrypt_generic_init($td, $key, $iv);


$decrypted_data = mdecrypt_generic($td, $input);


mcrypt_generic_deinit($td);


mcrypt_module_close($td);


return trim(chop($decrypted_data));


}

from:http://www.cnblogs.com/cocowool/archive/2009/01/07/1371309.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: