This article mainly introduces the example of php encryption and decryption. For more information, see.
The Code is as follows:
$ Id = "http://www.php.net ";
$ Token = encrypt ($ id, 'E', 'php ');
Echo 'encryption: '. encrypt ($ id, 'E', 'php ');
Echo'
';
Echo 'decryption: '. encrypt ($ token, 'D', 'php ');
/*************************************** ******************************
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;
}
}
?>