Two classic PHP encryption and decryption functions are shared

  • 2021-07-06 10:25:54
  • OfStack

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

The author included a more classic PHP encryption and decryption function code, to share with you. Encryption and decryption principle 1 is generally through a fixed encryption and decryption algorithm, the key is added to the algorithm, and finally the encryption and decryption results are obtained.
1, very powerful authcode encryption function, Discuz! Classic code (with detailed explanation):


function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {  
    // Dynamic key length, the same plaintext will generate different ciphertext, which depends on dynamic key   
    $ckey_length = 4;  
      
    // Secret key   
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);  
      
    // Secret key a Will participate in encryption and decryption   
    $keya = md5(substr($key, 0, 16));  
    // Secret key b Will be used for data integrity verification   
    $keyb = md5(substr($key, 16, 16));  
    // Secret key c Used to change the generated ciphertext   
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length):
substr(md5(microtime()), -$ckey_length)) : '';  
    // Key participating in the operation   
    $cryptkey = $keya.md5($keya.$keyc);  
    $key_length = strlen($cryptkey);  
    // Clear text, before 10 Bits are used to hold timestamps, verify the validity of data when decrypting, 10 To 26 Bit is used to save $keyb( Secret key b) ,
// This key verifies data integrity when decrypting   
    // If it is decoded, it will start from the first $ckey_length Bit, because the ciphertext is preceded by $ckey_length Bit saving Dynamic key to ensure correct decryption   
    $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();  
    // Generate a key book   
    for($i = 0; $i <= 255; $i++) {  
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);  
    }  
    // Using a fixed algorithm, disrupting the key book and increasing randomness seems to be very complicated, but in fact it will not increase the strength of the ciphertext   
    for($j = $i = 0; $i < 256; $i++) {  
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;  
        $tmp = $box[$i];  
        $box[$i] = $box[$j];  
        $box[$j] = $tmp;  
    }  
    // Core encryption and decryption part   
    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;  
        // The key obtained from the key book is XOR, and then converted into characters   
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));  
    }  
    if($operation == 'DECODE') { 
        // To verify the validity of data, see the format of unencrypted plaintext   
        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 {  
        // Save the dynamic key in ciphertext, which is why the same plaintext can be decrypted after producing different ciphertext   
        // Because the encrypted ciphertext may be 1 Some special characters may be lost during copying, so use base64 Code   
        return $keyc.str_replace('=', '', base64_encode($result));  
    }  
}

$string in functions authcode ($string, $operation, $key, $expiry): String, plaintext, or ciphertext; $operation: DECODE for decryption, others for encryption; $key: Key; $expiry: The ciphertext is valid.

Usage:

 
$str = 'abcdef';
$key = 'www.helloweba.com';
echo authcode($str,'ENCODE',$key,0); // Encryption
$str = '56f4yER1DI2WTzWMqsfPpS9hwyoJnFP2MpC8SOhRrxO7BOk';
echo authcode($str,'DECODE',$key,0); // Decryption

2. Encryption and decryption function encrypt ():

function encrypt($string,$operation,$key=''){ 
    $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<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,0,8)==substr(md5(substr($result,8).$key),0,8)){
            return substr($result,8);
        }else{
            return'';
        }
    }else{
        return str_replace('=','',base64_encode($result));
    }
}

In function encrypt ($string, $operation, $key), $string: The string to be encrypted and decrypted; $operation: Judge whether to encrypt or decrypt, E means encrypt, D means decrypt; $key: Key.
Usage:

 
$str = 'abc';
$key = 'www.helloweba.com';
$token = encrypt($str, 'E', $key);
echo ' Encryption :'.encrypt($str, 'E', $key);
echo ' Decryption: '.encrypt($str, 'D', $key);

PS: About encryption technology, this site also provides the following encryption tools for your reference:

MD5 Online Encryption Tool: http://tools.ofstack.com/password/CreateMD5Password

Escape Encryption/Decryption Tool: http://tools.ofstack.com/password/escapepwd

Online SHA1 encryption tool: http://tools.ofstack.com/password/sha1encode

Short chain (short website) online generation tool: http://tools.ofstack.com/password/dwzcreate

Short chain (short website) online restoration tool: http://tools.ofstack.com/password/unshorturl

High strength cryptographic generator: http://tools.ofstack.com/password/CreateStrongPassword


Related articles: