PHP加密解密函數收藏

來源:互聯網
上載者:User
在PHP開發中,很多時候我們需要對資料進行加密解密,比如有些資料需要儲存到cookie中,但又不能被使用者輕易得到這些資料,這時我們就需要加密這些資料儲存到cookie中,等我們需要使用它們的時候再解密。

加密的過程如下:

// 加密資料並寫到cookie裡$cookie_data = $this -> encrypt("scutephp.com", $data);                     $cookie = array(    'name'   => '$data',    'value'  => $cookie_data,    'expire' => $user_expire,    'domain' => '',    'path'   => '/',    'prefix' => '');$this->input->set_cookie($cookie);     // 加密public function encrypt($key, $plain_text) {       $plain_text = trim($plain_text);       $iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));       $c_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $plain_text, MCRYPT_ENCRYPT, $iv);       return trim(chop(base64_encode($c_t)));   }

使用的時候再解密:

if( isset($_COOKIE['data']) ){    //用cookie給session賦值    $_SESSION['data'] = decrypt("nowamagic", $_COOKIE['data']);}   function decrypt($key, $c_t) {       $c_t = trim(chop(base64_decode($c_t)));       $iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));       $p_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $c_t, MCRYPT_DECRYPT, $iv);       return trim(chop($p_t));   }

這裡記錄下這個可逆的加密函數的使用。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.