


Four useful PHP custom encryption functions (reversible/irreversible)
Sometimes in the project we need to use PHP to encrypt specific information, that is, to generate an encrypted string through the encryption algorithm. These encrypted strings can be decrypted through the decryption algorithm to facilitate the program to process the decrypted information. .
The most common applications are in user login and some API data exchange scenarios. The most common applications are in user login and some API data exchange scenarios. The principle of encryption and decryption is generally to use a certain encryption and decryption algorithm, add the key to the algorithm, and finally obtain the encryption and decryption results.
Without further ado, let’s get straight to the code.
1. The first reversible encryption function for ID can also be used for invitation codes and the like. The decrypted data is relatively simple
Example: lockcode(28)=》 000X unlockcode('000X')=》28
//加密函数 function lockcode($code) { static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ'; $num = $code; $code = ''; while ( $num > 0) { $mod = $num % 35; $num = ($num - $mod) / 35; $code = $source_string[$mod].$code; } if(empty($code[3])) $code = str_pad($code,4,'0',STR_PAD_LEFT); return $code; } //解密函数 function unlockcode($code) { static $source_string = 'E5FCDG3HQA4B1NOPIJ2RSTUV67MWX89KLYZ'; if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0')+1); $len = strlen($code); $code = strrev($code); $num = 0; for ($i=0; $i < $len; $i++) { $num += strpos($source_string, $code[$i]) * pow(35, $i); } return $num; }
2. The second is the encryption function that I searched on the Internet. It is very easy to use, reversible encryption, and supports salt parameters.
Example:
encrypt('abcd','1234')=》nkiV93IfJ decrypt('nkiV93IfJ','1234')=》abcd
//加密函数 function encrypt($data,$key='CHENI'){ $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; $nh = rand(0,64); $ch = $chars[$nh]; $mdKey = md5($key.$ch); $mdKey = substr($mdKey,$nh%8, $nh%8+7); $data= base64_encode($data); $tmp = ''; $i=0;$j=0;$k = 0; for ($i=0; $i<strlen($data); $i++) { $k = $k == strlen($mdKey) ? 0 : $k; $j = ($nh+strpos($chars,$data[$i])+ord($mdKey[$k++]))%64; $tmp .= $chars[$j]; } return urlencode($ch.$tmp); } //解密函数 function decrypt($data,$key='CHENI'){ $txt = urldecode($data); $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; $ch = $txt[0]; $nh = strpos($chars,$ch); $mdKey = md5($key.$ch); $mdKey = substr($mdKey,$nh%8, $nh%8+7); $txt = substr($txt,1); $tmp = ''; $i=0;$j=0; $k = 0; for ($i=0; $i<strlen($txt); $i++) { $k = $k == strlen($mdKey) ? 0 : $k; $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]); while ($j<0) $j+=64; $tmp .= $chars[$j]; } return base64_decode($tmp); }
Third, the third type is similar to the above, and also supports salt value parameters
Example: encrypt('abcd','1234')=》mZPHxw== decrypt( 'mZPHxw==','1234')=》abcd
function encrypt($data, $key) { $char=""; $str=""; $key = md5($key); $x = 0; $len = strlen($data); $l = strlen($key); for ($i = 0; $i < $len; $i++) { if ($x == $l) { $x = 0; } $char .= $key{$x}; $x++; } for ($i = 0; $i < $len; $i++){ $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256); } return base64_encode($str); } function decrypt($data, $key) { $key = md5($key); $x = 0; $data = base64_decode($data); $len = strlen($data); $l = strlen($key); for ($i = 0; $i < $len; $i++) { if ($x == $l){ $x = 0;} $char .= substr($key, $x, 1); $x++; } for ($i = 0; $i < $len; $i++){ if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1))){ $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1))); }else{ $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1))); } } return $str; }
4. This is the best one I have ever used, the encryption and decryption algorithm used in discuz
//加密算法 function authcode($string,$key='',$operation=false,$expiry=0){ $ckey_length = 4; $key = md5($key ? $key : DEFAULT_KEYS); $keya = md5(substr($key, 0, 16)); $keyb = md5(substr($key, 16, 16)); $keyc = $ckey_length ? ($operation? substr($string, 0, $ckey_length):substr(md5(microtime()), -$ckey_length)) : ''; $cryptkey = $keya.md5($keya.$keyc); $key_length = strlen($cryptkey); $string = $operation? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string; $string_length = strlen($string); $result = ''; $box = range(0, 255); $rndkey = array(); for($i = 0; $i <= 255; $i++) { $rndkey[$i] = ord($cryptkey[$i % $key_length]); } for($j = $i = 0; $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) { if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) { return substr($result, 26); } else { return ''; } } else { return $keyc.str_replace('=', '', base64_encode($result)); } } echo authcode('123456','key'); echo '<br>'; echo authcode('7d49kn9k07uSBZvha8as+/qm4UoLfpy88PFg12glPeDtlzc','key',true);
For more PHP related knowledge, please visit PHP Tutorial!
The above is the detailed content of Four useful PHP custom encryption functions (reversible/irreversible). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
