search
HomeBackend DevelopmentPHP TutorialPHP encryption and decryption functions generate encrypted and decrypted strings

PHP encryption and decryption function sharing, one is Discuz!'s authcode encryption function (with detailed decomposition), and the other is the encrypt() function. PHP needs to be used to encrypt specific information, that is, an encrypted string is generated through the encryption algorithm. This encrypted string can be decrypted through the decryption algorithm to facilitate the program to process the decrypted information.

Sometimes in the project we need to use PHP to encrypt specific information, that is, to generate an encrypted string through the encryption algorithm. This encrypted string can be decrypted through the decryption algorithm, which facilitates the program to decrypt the decrypted string. Information is processed.
The most common applications are in user login and some API data exchange scenarios.

The author has collected some classic PHP encryption and decryption function codes to share with you. 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.

1. A very powerful authcode encryption function, Discuz! Classic code (with detailed explanation):

function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {  
  // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙  
  $ckey_length = 4;  
    
  // 密匙  
  $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);  
    
  // 密匙a会参与加解密  
  $keya = md5(substr($key, 0, 16));  
  // 密匙b会用来做数据完整性验证  
  $keyb = md5(substr($key, 16, 16));  
  // 密匙c用于变化生成的密文  
  $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): 
substr(md5(microtime()), -$ckey_length)) : '';  
  // 参与运算的密匙  
  $cryptkey = $keya.md5($keya.$keyc);  
  $key_length = strlen($cryptkey);  
  // 明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b), 
//解密时会通过这个密匙验证数据完整性  
  // 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确  
  $string = $operation == 'DECODE' ? 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 == &#39;DECODE&#39;) { 
    // 验证数据有效性,请看未加密明文的格式  
    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 &#39;&#39;;  
    }  
  } else {  
    // 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因  
    // 因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码  
    return $keyc.str_replace(&#39;=&#39;, &#39;&#39;, base64_encode($result));  
  }  
}

$string in function authcode($string, $operation, $key, $expiry) : String, plaintext or ciphertext; $operation: DECODE means decryption, others means encryption; $key: encryption key; $expiry: ciphertext validity period.
Usage:

$str = &#39;abcdef&#39;; 
$key = &#39;www.helloweba.com&#39;; 
echo authcode($str,&#39;ENCODE&#39;,$key,0); //加密 
$str = &#39;56f4yER1DI2WTzWMqsfPpS9hwyoJnFP2MpC8SOhRrxO7BOk&#39;; 
echo authcode($str,&#39;DECODE&#39;,$key,0); //解密

2. Encryption and decryption function encrypt():

function encrypt($string,$operation,$key=&#39;&#39;){ 
  $key=md5($key); 
  $key_length=strlen($key); 
   $string=$operation==&#39;D&#39;?base64_decode($string):substr(md5($string.$key),0,8).$string; 
  $string_length=strlen($string); 
  $rndkey=$box=array(); 
  $result=&#39;&#39;; 
  for($i=0;$i<=255;$i++){ 
      $rndkey[$i]=ord($key[$i%$key_length]); 
    $box[$i]=$i; 
  } 
  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==&#39;D&#39;){ 
    if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){ 
      return substr($result,8); 
    }else{ 
      return&#39;&#39;; 
    } 
  }else{ 
    return str_replace(&#39;=&#39;,&#39;&#39;,base64_encode($result)); 
  } 
}

$string in function encrypt($string,$operation,$key): the string that needs to be encrypted and decrypted ;$operation: determine whether to encrypt or decrypt, E means encryption, D means decryption; $key: key.
Usage:

$str = &#39;abc&#39;; 
$key = &#39;www.helloweba.com&#39;; 
$token = encrypt($str, &#39;E&#39;, $key); 
echo &#39;加密:&#39;.encrypt($str, &#39;E&#39;, $key); 
echo &#39;解密:&#39;.encrypt($str, &#39;D&#39;, $key);

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

PHP connects to Baidu through Ajax calls to realize the function of detecting whether the website is connected to the Internet

The concept and characteristics of PHP singleton mode

The definition of the static keyword in PHP, late binding and the difference from the self keyword

The above is the detailed content of PHP encryption and decryption functions generate encrypted and decrypted strings. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

How often should you regenerate session IDs?How often should you regenerate session IDs?Apr 23, 2025 am 12:03 AM

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

How do you set the session cookie parameters in PHP?How do you set the session cookie parameters in PHP?Apr 22, 2025 pm 05:33 PM

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

What is the main purpose of using sessions in PHP?What is the main purpose of using sessions in PHP?Apr 22, 2025 pm 05:25 PM

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How can you share sessions across subdomains?How can you share sessions across subdomains?Apr 22, 2025 pm 05:21 PM

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)