PHP使用DES进行加密和解密

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));

    }   

 

 

posted @ 2009-01-07 18:07  Cocowool  阅读(29749)  评论(1编辑  收藏  举报