This article mainly introduces the example of php encryption and decryption. For more information, see.
The code is as follows:
$ Id = "http://www.bitsCN.com ";
$ Token = encrypt ($ id, 'e', 'jb51 ');
Echo 'encryption: '. encrypt ($ id, 'e', 'jb51 ');
Echo'
';
Echo 'decryption: '. encrypt ($ token, 'D', 'jb51 ');
/*************************************** ******************************
Function name: encrypt
Function: encrypts and decrypts strings.
Usage:
Encryption: encrypt ('str', 'e', 'qingdou ');
Decryption: encrypt ('encrypted string', 'D', 'qingdou ');
Parameter description:
$ String: string to be encrypted and decrypted
$ Operation: determine whether to encrypt or decrypt: E: encrypt D: decrypt
$ Key: the encrypted key (key );
**************************************** *****************************/
Function encrypt ($ string, $ operation, $ key = '')
{
$ Src = array ("/", "+", "= ");
$ Dist = array ("_ a", "_ B", "_ c ");
If ($ operation = 'd') {$ string = str_replace ($ dist, $ src, $ string );}
$ Key = md5 ($ key );
$ Key_length = strlen ($ key );
$ String = $ operation = 'D '? Base64_decode ($ string): substr (md5 ($ string. $ key), 0, 8). $ string;
$ String_length = strlen ($ string );
$ Rndkey = $ box = array ();
$ Result = '';
For ($ I = 0; $ I <= 255; $ I ++)
{
$ Rndkey [$ I] = ord ($ key [$ I % $ key_length]);
$ Box [$ I] = $ I;
}
For ($ j = $ I = 0; I I <256; $ I ++)
{
$ J = ($ j + $ box [$ I] + $ rndkey [$ I]) % 256;
$ Tmp = $ box [$ I];
$ Box [$ I] = $ box [$ j];
$ Box [$ j] = $ tmp;
}
For ($ a = $ j = $ I = 0; $ I <$ string_length; $ I ++)
{
$ A = ($ a + 1) % 256;
$ J = ($ j + $ box [$ a]) % 256;
$ Tmp = $ box [$ a];
$ Box [$ a] = $ box [$ j];
$ Box [$ j] = $ tmp;
$ Result. = chr (ord ($ string [$ I]) ^ ($ box [($ box [$ a] + $ box [$ j]) % 256]);
}
If ($ operation = 'd ')
{
If (substr ($ result,) = substr (md5 (substr ($ result, 8). $ key ))
{
Return substr ($ result, 8 );
}
Else
{
Return '';
}
}
Else
{
$ Rdate = str_replace ('=', '', base64_encode ($ result ));
$ Rdate = str_replace ($ src, $ dist, $ rdate );
Return $ rdate;
}
}
?>