Encrypt and decrypt cookies (LOGIN Operation)

Source: Internet
Author: User
Provides various official and user-released code examples. For code reference, you are welcome to exchange and learn. encryption of cookies makes your website more secure and logon information is not stored in the session.
Create two functions in the function. php file to encrypt and decrypt the functions. /**
* Encryption functions
* @ Param string $ txt the string to be encrypted
* @ Param string $ key
* @ Return string returns the encrypted result.
*/
Function encrypt ($ txt, $ key = ''){
If (empty ($ txt) return $ txt;
If (empty ($ key) $ key = md5 (MD5_KEY );
$ Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 -_.";
$ Ikey = "-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm ";
$ Nh1 = rand (0, 64 );
$ H2= rand (0, 64 );
$ NH 3 = rand (0, 64 );
$ Region = $ chars {$ nh1 };
$ Ch2 = $ chars {$ h2 };
$ Ch3 = $ chars {$ NH 3 };
$ Nhnum = $ nh1 + $ NH 2 + $ NH 3;
$ Knum = 0; $ I = 0;
While (isset ($ key {$ I}) $ knum + = ord ($ key {$ I ++ });
$ MdKey = substr (md5 (md5 (md5 ($ key. $ snapshots ). $ ch2. $ ikey ). $ ch3), $ nhnum % 8, $ knum % 8 + 16 );
$ Txt = base64_encode (time (). '_'. $ txt );
$ Txt = str_replace (array ('+', '/', '='), array ('-', '_', '.'), $ txt );
$ Tmp = '';
$ J = 0; $ k = 0;
$ Tlen = strlen ($ txt );
$ Klen = strlen ($ mdKey );
For ($ I = 0; $ I <$ tlen; $ I ++ ){
$ K = $ klen? 0: $ k;
$ J = ($ nhnum + strpos ($ chars, $ txt {$ I}) + ord ($ mdKey {$ k ++}) % 64;
$ Tmp. = $ chars {$ j };
}
$ Tmplen = strlen ($ tmp );
$ Tmp = substr_replace ($ tmp, $ ch3, $ h2% ++ $ tmplen, 0 );
$ Tmp = substr_replace ($ tmp, $ ch2, $ nh1 % + + $ tmplen, 0 );
$ Tmp = substr_replace ($ tmp, $ replace, $ knum % ++ $ tmplen, 0 );
Return $ tmp;
}

/**
* Decryption Function
* @ Param string $ txt the string to be decrypted
* @ Param string $ key
* @ Return string type returned results
*/
Function decrypt ($ txt, $ key = '', $ ttl = 0 ){
If (empty ($ txt) return $ txt;
If (empty ($ key) $ key = md5 (MD5_KEY );

$ Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 -_.";
$ Ikey = "-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm ";
$ Knum = 0; $ I = 0;
$ Tlen = @ strlen ($ txt );
While (isset ($ key {$ I}) $ knum + = ord ($ key {$ I ++ });
$ Scheme = @ $ txt {$ knum % $ tlen };
$ Nh1 = strpos ($ chars, $ bytes );
$ Txt = @ substr_replace ($ txt, '', $ knum % $ tlen --, 1 );
$ Ch2 =@ $ txt {$ nh1 % $ tlen };
$ H2=@ strpos ($ chars, $ ch2 );
$ Txt = @ substr_replace ($ txt, '', $ nh1 % $ tlen --, 1 );
$ Ch3 =@ $ txt {nh2 h2% $ tlen };
$ NH 3 = @ strpos ($ chars, $ ch3 );
$ Txt = @ substr_replace ($ txt, '', $ h2% $ tlen --, 1 );
$ Nhnum = $ nh1 + $ NH 2 + $ NH 3;
$ MdKey = substr (md5 (md5 (md5 ($ key. $ snapshots ). $ ch2. $ ikey ). $ ch3), $ nhnum % 8, $ knum % 8 + 16 );
$ Tmp = '';
$ J = 0; $ k = 0;
$ Tlen = @ strlen ($ txt );
$ Klen = @ strlen ($ mdKey );
For ($ I = 0; $ I <$ tlen; $ I ++ ){
$ K = $ klen? 0: $ k;
$ J = strpos ($ chars, $ txt {$ I})-$ nhnum-ord ($ mdKey {$ k ++ });
While ($ j <0) $ j + = 64;
$ Tmp. = $ chars {$ j };
}
$ Tmp = str_replace (array ('-', '_', '.'), array ('+', '/', '='), $ tmp );
$ Tmp = trim (base64_decode ($ tmp ));

If (preg_match ("/\ d {10} _/s", substr ($ tmp, 0, 11 ))){
If ($ ttl> 0 & (time ()-substr ($ tmp, 0, 11)> $ ttl )){
$ Tmp = null;
} Else {
$ Tmp = substr ($ tmp, 11 );
}
}
Return $ tmp;
}
Operations on the logon page of the background System // Log on
Public function login (){
If (IS_POST ){
// Verify the verification code
If (! $ This-> checkverify (I ('Post. captcha '))){
$ This-> error (L ('verify _ error'); // L function facilitates multi-language systems. The content is "Verification code error"
}
$ Admin = D ('admin ');
$ Res = $ Admin-> checkLogin (I ('Post. name '), I ('Post. pass '); // In the model, use M ('admin')-> where (array ('admin _ name' => $ name, 'admin _ password' => $ pass)-> find ();
If (is_array ($ res )&&! Empty ($ res )){
// Admin_name user name. Amdin_id primary key. Admin_gid is the permission group id. Admin_is_super is a super Administrator
$ Data = array ('name' => $ res ['admin _ name'], 'id' => $ res ['admin _ id'], 'gid' => $ res ['admin _ gid'], 'SP '=> $ res ['admin _ is_super']);
$ This-> systemSetKey ($ data );
$ This-> redirect (U ('index/Index '));
} Else {
$ This-> error (L ('user _ pass_error '); // L function facilitates multi-language systems with the content "incorrect user name or password"
}
} Else {
$ This-> display ();
}
}
Private function systemSetKey ($ user = ''){
If (is_array ($ user )&&! Empty ($ user )){
Cookie (COOKIE_PRE. 'sys _ key', encrypt (serialize ($ user), MD5_KEY), 3600); // The COOKIE_PRE here is a constant. You can define a constant directly in the entry file. User is a data and serialized into a string
}
}
How to verify administrator information on the homepage of the background System
Write verification in the base class Namespace Admin \ Controller;
Use Think \ Controller;
Class BaseController extends Controller {
Protected $ admin_info; // administrator information name id group
Protected $ permission; // permission content

Public function _ construct (){
/**
* Verify that the user has logged on.
* $ Admin_info administrator information name id
* 1 is the Super administrator.
*/
$ This-> admin_info = $ this-> systemLogin ();
If ($ this-> admin_info ['id']! = 1 ){
// Verify the permission, which is omitted

}
Parent: :__ construct ();
}

/**
* System background logon Verification
*
* @ Param
* @ Return array returned results
*/
Protected final function systemLogin (){
// Obtain the cookie content, decrypt it, and match it with the System
$ User = unserialize (decrypt (cookie (COOKIE_PRE. 'sys _ key'), MD5_KEY ));
If (! Key_exists ('gid', (array) $ user) |! Isset ($ user ['SP ']) | (empty ($ user ['name']) | empty ($ user ['id']) {
$ This-> redirect (U ('Public/login '));
} Else {
$ This-> systemSetKey ($ user );
}
Return $ user;
}
/**
* After a system background member logs on, the member verification content is written into the corresponding cookie.
* @ Param string $ name Username
* @ Param int $ id user id
* @ Return Boolean return result
*/
Protected final function systemSetKey ($ user ){
Cookie (COOKIE_PRE. 'sys _ key', encrypt (serialize ($ user), MD5_KEY), 3600 );
}
}

AD: truly free, domain name + VM + enterprise mailbox = 0 RMB

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.