This article introduces three commonly used PHP encryption and decryption algorithm, there is a certain reference value, there is a need for a friend can refer to it, I hope to help you.

phpBuilt-in encryption function:

The irreversible encryption functions are md5(), sha1() and crypt().

  1. md5()Used to calculate MD5 hash
md5(string $str[,bool $raw_output=FALSE] ) :string
Copy the code

Use:

/** * MD5 takes two arguments: * First argument: encrypted string * second argument: if set to TRUE returns the raw binary format of 16 bytes, default false returns the hash value in 32-bit hexadecimal number */
$str = '123456789';
echo 'Default MD5 encrypted string is:'.md5($str)."\r\n";   //25f9e794323b453885f5181f1b624d0b
echo 'The second argument is TRUE. The MD5 encrypted string is:'..md5($str.true)."\n"; / / % � � 2; E8 � � bM
Copy the code
  1. Sha1 () – Evaluates the SHA1 hash value of the string
sha1(string $str[,bool $raw_output= false] ) :string
Copy the code

Use:

/** * sha1 takes two arguments: * First argument: encrypted string * second argument: if set to TRUE returns the raw binary format of 20 bytes, default false returns the hash value in the form of a 40 character hexadecimal number */
$str = '123456789';
echo 'The default sha1 encrypted string is:'.sha1($str)."\r\n";   //d0be2dc421be4fcd0172e5afceea3970e2f3d940
echo 'The second argument is TRUE. The sha1 encrypted string is:'..sha1($str.true)."\n"; / / % � � 2; E8 � � bM
Copy the code
  1. Crypt () encrypts the string using UNIX’s standard encryption DES module. This is a one-way encryption function and cannot be decrypted. To compare strings, place the first two characters of the encrypted string in the argument to salt and compare the encrypted string.
crypt(string $str[,string $salt] ) :string
Copy the code

Use:

/** * crypt takes two arguments: * first argument: encryption string * second argument: salt string */
$str = '123456789';
// Use automatic salt values
echo Automatic Salt value: . crypt($str)."\n";   // $1$yvnZHBo0$sBZBd0vzZYnxbtQftQulZ/
// Use crypt() with different hash types
/** * CRYPT_STD_DES - Hashes based on the standard DES algorithm use two characters in the "./ 0-9a-za-z "character as salt values. Using illegal characters in salt values will cause crypt() to fail. * CRYPT_EXT_DES - Extended hash based on DES algorithm. Its salt value is a string of 9 characters, consisting of an underscore followed by a 4-byte loop number and a 4-byte salt value. They are encoded as printable characters of 6 bits each, with the fewest significant bits taking precedence. 0 to 63 are encoded as "./ 0-9A-zA-z ". Using illegal characters in salt values will cause crypt() to fail. * crypt_md5-MD5 hash uses a 12-character string salt value starting with $1$. * The crypt_blowfish-blowfish algorithm uses the following salt values: "$2a$", a two-digit cost parameter," $", and a 64-bit string composed of the characters in "./ 0-9a-za-z ". Using characters outside this range in salt values causes crypt() to return an empty string. The two-digit cost parameter is the logarithm base 2 of the number of cycles, which ranges from 04 to 31, beyond which crypt() will fail. Before PHP 5.3.7 only supported "$2a$" as a salt prefix, PHP 5.3.7 introduced a new prefix to fix a security risk in the Blowfish implementation. See » This document for more information about this fix. In summary, developers developing only for PHP 5.3.7 and later should use "$2Y $" instead of" $2a$" * the crypt_sha256-SHA-256 algorithm hases a 16-character string salt starting with $5$. If the salt string starts with "rounds=
      
       $", the numeric value of N will be used to specify how many times the hash loop is executed, much like the cost parameter in the Blowfish algorithm. The default number of loops is 5000, the minimum is 1000, and the maximum is 999,999,999. N beyond this range will be converted to the nearest value. * The crypt_sha512-SHA-512 algorithm hashes a 16-character string salt starting with $6$. If the salt string starts with "rounds=
       
        $", the numeric value of N will be used to specify how many times the hash loop is executed, much like the cost parameter in the Blowfish algorithm. The default number of loops is 5000, the minimum is 1000, and the maximum is 999,999,999. N beyond this range will be converted to the nearest value. * /
       
      
echo 'CRYPT_STD_DES: ' . crypt($str.'rl')."\n";
echo 'CRYPT_EXT_DES(extended DES): ' . crypt($str.'_J9.. rasm')."\n";
echo 'CRYPT_MD5(MD5): ' . crypt($str.'$1$rasmusle$')."\n";
echo 'CRYPT_BLOWFISH(Blowfish): ' . crypt($str.'$2a$07$usesomesillystringforsalt$')."\n";
echo 'CRYPT_SHA256(SHA-256): ' . crypt($str.'$5$rounds=5000$usesomesillystringforsalt$')."\n";
echo 'CRYPT_SHA512(SHA-512): ' . crypt($str.'$6$rounds=5000$usesomesillystringforsalt$')."\n";
Copy the code

Reversible encryption is: base64_encode(), urlencode(), McRypt_encrypt (), rawurlencode()

Corresponding decryption functions: base64_decode(), urldecode(), McRypt_decrypt (), rawurldecode()

  1. McRypt_encrypt () – Encrypts the plaintext with the given parameter
mcrypt_encrypt(string $cipher, string $key, string $data, string $mode[, string $iv] ) :string
Copy the code

Use:

/** * McRypt_encrypt takes two arguments: * The first argument: the algorithm name for the string value MCRYPT_RIJNDAEL_256, MCRYPT_RIJNDAEL_128, MCRYPT_RIJNDAEL_192 * The second argument: Encryption key If the key length is not a valid length supported by the algorithm, the function will issue a warning and return FALSE * third argument: encrypted data * Fourth argument: MCRYPT_MODE_modename one of the constants, or one of the following strings: "ECB", "CBC", "CFB", "OFB", "NOFB" and "stream". * The fifth parameter: iv is generally the encrypted key */
$key = 'password';  // Encryption key
$str = '123456789'; // Encrypt data
echo 'McRypt_encrypt Encryption:' . mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $str, MCRYPT_MODE_CBC, md5(md5($key)))."\n";
Copy the code
  1. Base64_encode () – Encodes data using MIME base64
base64_encode (string $data):string
Copy the code

Use:

$str = 'This is an encoded string';
echo base64_encode($str);
Copy the code
  1. Urlencode ()/rawurlencode() – Encodes the URL string
urlencode (string $str):string
Copy the code

Use:

$str = 'https://www.baidu.com';
echo urlencode($str);
Copy the code

Custom encryption functions:

  1. The first kind of customization:
function encryptDecrypt($key.$string.$decrypt){   
    if($decrypt) {$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");   
        return $decrypted;   
    }else{   
        $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));   
        return $encrypted; }}/ / encryption:
echo encryptDecrypt('password'.'Helloweba welcome you '.0); 

/ / decryption:
echo encryptDecrypt('password'.'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk='.1); 
Copy the code
  1. Second customization:
/ / encryption
function lock_url($txt.$key='blog.qsjob.top'){  
    $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";  
    $nh = rand(0.64);  
    $ch = $chars[$nh];  
    $mdKey = md5($key.$ch);  
    $mdKey = substr($mdKey.$nh%8.$nh%8+7);  
    $txt = base64_encode($txt);  
    $tmp = ' ';  
    $i=0;$j=0;$k = 0;  
    for ($i=0; $i<strlen($txt); $i{+ +)$k = $k == strlen($mdKey)?0 : $k;  
        $j = ($nh+strpos($chars.$txt[$i])+ord($mdKey[$k+ +)) %64;  
        $tmp. =$chars[$j];  
    }  
    return urlencode($ch.$tmp);  
}
/ / decryption
function unlock_url($txt.$key='blog.qsjob.top'){  
    $txt = urldecode($txt);  
    $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);  
} 

/ / encryption
echo lock_url('This is the second custom encryption and decryption function');
/ / decryption
echo unlock_url(lock_url('This is the second custom encryption and decryption function'));
Copy the code
  1. Third customization:
/ / encryption
function passport_encrypt($txt.$key = 'blog.qsjob.top') {   
    srand((double)microtime() * 1000000);   
    $encrypt_key = md5(rand(0.32000));   
    $ctr = 0;   
    $tmp = ' ';   
    for($i = 0;$i < strlen($txt); $i{+ +)$ctr = $ctr == strlen($encrypt_key)?0 : $ctr;   
    $tmp. =$encrypt_key[$ctr]. ($txt[$i] ^ $encrypt_key[$ctr+ +]); }return urlencode(base64_encode(passport_key($tmp.$key)));   
}  
/ / decryption
function passport_decrypt($txt.$key = 'blog.qsjob.top') {   
    $txt = passport_key(base64_decode(urldecode($txt)), $key);   
    $tmp = ' ';   
    for($i = 0;$i < strlen($txt); $i{+ +)$md5 = $txt[$i];   
    $tmp. =$txt[+ +$i] ^ $md5;   
    }   
    return $tmp;   
}   
// Parse the algorithm
function passport_key($txt.$encrypt_key) {   
    $encrypt_key = md5($encrypt_key);   
    $ctr = 0;   
    $tmp = ' ';   
    for($i = 0; $i < strlen($txt); $i{+ +)$ctr = $ctr == strlen($encrypt_key)?0 : $ctr;   
    $tmp. =$txt[$i] ^ $encrypt_key[$ctr+ +]; }return $tmp;   
} 
$txt = "1"; // Encrypt data
$key = "testkey"; // Encryption key
/ / encryption
$encrypt = passport_encrypt($txt.$key); 
echo $encrypt; 
/ / decryption
echo passport_decrypt($encrypt.$key); 
Copy the code
  1. The fourth kind of customization:
// authCode encryption function Discuz! Classic code (with detailed explanation)
$string in the function authCode ($string, $operation, $key, $expiry) : string, clear text or ciphertext; $operation: DECODE indicates decryption, other indicates encryption; $key: the key; $expiry: Ciphertext expiry date.
function authcode($string.$operation = 'DECODE'.$key = ' '.$expiry = 0) {     
    // Dynamic key length, the same plaintext will generate different ciphertext depends on the dynamic key
    $ckey_length = 4;     
    / / key
    $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);     
    // Key A participates in decryption
    $keya = md5(substr($key.0.16));     
    // Key B is used to verify data integrity
    $keyb = md5(substr($key.16.16));     
    // Key C is used to change the generated ciphertext
    $keyc = $ckey_length ? ($operation= ='DECODE' ? substr($string.0.$ckey_length): substr(md5(microtime()), -$ckey_length)) : ' ';     
    // The key involved in the operation
    $cryptkey = $keya.md5($keya.$keyc);     
    $key_length = strlen($cryptkey);     
    // clear text, the first 10 bits are used to store the timestamp and verify the data validity when decrypting, 10 to 26 bits are used to store $keyb(keyb),
    // Data integrity will be verified by this key during decryption
    The $ckey_length bit before the ciphertext holds the dynamic key to ensure proper 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(a);// Generate the key book
    for($i = 0; $i< =255; $i{+ +)$rndkey[$i] = ord($cryptkey[$i % $key_length]);     
    }     
    // Using a fixed algorithm, shuffling the key book and increasing randomness may seem complicated, but actually it does 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;     
        // Extract the key from the key book for xor, and then convert it to a character
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));     
    }     
    if($operation= ='DECODE') {    
        // To verify data validity, 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 {     
        // The dynamic key is stored in ciphertext. This is why the same plain text can be decrypted after producing different ciphertext
        // Because the encrypted ciphertext may be some special characters, the replication process may be lost, so base64 encoding
        return $keyc.str_replace('='.' ', base64_encode($result)); }}$str = 'jobhansome';   
$key = 'blog.qsjob.top';   
echo authcode($str.'ENCODE'.$key.0); / / encryption
$str = '56f4yER1DI2WTzWMqsfPpS9hwyoJnFP2MpC8SOhRrxO7BOk';   
echo authcode($str.'DECODE'.$key.0); / / decryption
Copy the code

Conclusion: That’s all for this article.

If you are interested, feel free to discuss it and I will be waiting for you in the comments section!!

If you think the article is good, you can scan the code to pay attention to our public number oh ~ take you to read more excellent articles ~