A variety of encryption techniques and code examples in PHP parsing _php tips

Source: Internet
Author: User
Tags base64 first string openssl ord strlen urlencode alphanumeric characters asymmetric encryption

Symmetric encryption (also known as private key encryption) is the encryption and decryption algorithm that uses the same key to encrypt and decrypt. Sometimes called the traditional cipher algorithm, the encryption key can be inferred from the decryption key, while the decryption key can also be inferred from the encryption key. In most symmetric algorithms, the encryption key and encryption key is the same, so it is also called the secret key algorithm or the single key algorithm.

Classification of information encryption technology

Single hash encryption technology (irreversible encryption)

is a digest algorithm, is not a cryptographic algorithm, the role is to change any length of input string into a fixed length of the output string of a function


String MD5 (string $str [, bool $raw _output = false]); MD5 encryption, enter any length string to return a unique 32-bit character

MD5 () is one-way encryption, there is no reverse decryption algorithm, but still can be some common strings through the collection, enumeration, collision and other methods to crack; So in order to make it more troublesome to crack, so we generally add a little salt value (salt) and double MD5;

MD5 (MD5 ($password). ' Sdva ');

Sdva is the salt value, the salt value should be random, such as MD5 commonly used in password encryption, so in the registration I will randomly generate this string, and then through the above method to double encryption;


It is very rare to see someone use this function, if you want to use it may be used in a symmetric or asymmetric algorithm, to understand that can be;

String Crypt (String $str [, String $salt])//The first string to be encrypted, the second is a salt value (that is, the encrypted noise value, which is automatically generated by PHP if not provided); Returns a hash string or a word less than 13 characters String, the latter in order to distinguish the salt value

<?php $password = ' testtest.com '; 
Echo Crypt ($password); Output: $1$dz3. QX2. $CQZ 8I. 
OFEEPKYRWP0OG8L1/* The eight characters between the second $ and the third $ are generated by PHP, and each time it is refreshed it is changed once/echo " 

Asymmetric encryption

Asymmetric encryption algorithm requires two keys for encryption and decryption, the two secret keys are public key (publicly key, referred to as public key) and private key (private key, referred to as private key);

As shown in the figure, the use of asymmetric encryption between A and b completes the secure transmission of important information.

    • Party B generates a pair of keys (public and private) and exposes the public key to other parties.
    • The first party who obtains the public key uses the key to encrypt the confidential information and sends it to party B.
    • Party B will then use their own save another private key (private key) to decrypt the encrypted information. Party B can only use its private key (private key) to decrypt the information encrypted by the corresponding public key.

In the transmission process, even if the attacker intercepted the transmission of the ciphertext, and got the second public key, can not crack the ciphertext, because only B's private key to decrypt the text

Similarly, if B to reply to the encrypted message to a, then need a first public key to the disclosure of a to use for encryption, a self-preservation of the private key for decryption.

The main algorithms used in asymmetric encryption are: RSA, Elgamal, knapsack algorithm, Rabin, D-h, ECC (elliptic curve encryption algorithm) and so on. One of the most common algorithms we see is the RSA algorithm.

The following is a excerpt from the web of a section of PHP through OpenSSL to achieve asymmetric encryption algorithm

<?php/** * uses OpenSSL to implement asymmetric encryption * @since 2010-07-08/class Rsa {/** * Private key * * Private $_priv 
  /** * Public Key * * Private $_pubkey; 
  /** * The keys saving path * * Private $_keypath; /** * The construtor,the param $path is the keys saving path/Public function __construct ($path) {if (E Mptyempty ($path) | | 
    !is_dir ($path)) {throw new Exception (' must set the keys save Path '); 
  } $this->_keypath = $path; /** * Create the key pair,save the key to $this->_keypath/Public Function CreateKey () {$r = op 
    Enssl_pkey_new (); 
    Openssl_pkey_export ($r, $privKey); File_put_contents ($this->_keypath. Directory_separator. 
    ' Priv.key ', $privKey); 
    $this->_privkey = Openssl_pkey_get_public ($privKey); 
    $RP = Openssl_pkey_get_details ($r); 
    $pubKey = $rp [' key ']; File_put_contents ($this->_keypath. Directory_separator. 
    ' Pub.key ', $pubKey); $thIs->_pubkey = Openssl_pkey_get_public ($pubKey); /** * Setup The private key */Public Function Setupprivkey () {if (Is_resource ($this->_privkey)) 
    {return true; $file = $this->_keypath. Directory_separator. 
    ' Priv.key '; 
    $PRK = file_get_contents ($file); 
    $this->_privkey = openssl_pkey_get_private ($PRK); 
  return true; 
      /** * Setup The Public key */Public Function Setuppubkey () {if (Is_resource ($this->_pubkey)) { 
    return true; $file = $this->_keypath. Directory_separator. 
    ' Pub.key '; 
    $puk = file_get_contents ($file); 
    $this->_pubkey = Openssl_pkey_get_public ($PUK); 
  return true; 
      }/** * Encrypt with the private key */Public Function Privencrypt ($data) {if (!is_string ($data)) { 
    return null; 
    } $this->setupprivkey (); 
    $r = Openssl_private_encrypt ($data, $encrypted, $this->_privkey); if ($r) {return Base64_encode ($encrypted); 
  return null; }/** * Decrypt with the private key/Public function Privdecrypt ($encrypted) {if!is_string ($encry 
    pted)) {return null; 
    } $this->setupprivkey (); 
    $encrypted = Base64_decode ($encrypted); 
    $r = Openssl_private_decrypt ($encrypted, $decrypted, $this->_privkey); 
    if ($r) {return $decrypted; 
  return null; 
      /** * Encrypt with public key */Public Function Pubencrypt ($data) {if (!is_string ($data)) { 
    return null; 
    } $this->setuppubkey (); 
    $r = Openssl_public_encrypt ($data, $encrypted, $this->_pubkey); 
    if ($r) {return base64_encode ($encrypted); 
  return null;  }/** * Decrypt with the public key */Public Function Pubdecrypt ($crypted) {if (!is_string ($crypted)) 
    {return null; 
    } $this->setuppubkey (); 
    $crypted = Base64_decode ($crypted); $r =Openssl_public_decrypt ($crypted, $decrypted, $this->_pubkey); 
    if ($r) {return $decrypted; 
  return null; 
    The Public Function __destruct () {@fclose ($this->_privkey); 
  @fclose ($this->_pubkey); 
}//Below is a simple test demo, if you do not need to delete $rsa = new RSA (' Ssl-key '); 
Private key encryption, public key decryption echo ' Source: I am old turtle <br/> '; 
$pre = $rsa->privencrypt (' I am old turtle '); echo ' Private encrypted:<br/> '. $pre. 
' <br/> '; 
$pud = $rsa->pubdecrypt ($pre); Echo ' Public decrypted: '. $pud. 
' <br/> '; 
Public key encryption, private key decryption echo ' Source: Dry it <br/> '; 
$pue = $rsa->pubencrypt (' dry it '); echo ' Public encrypt:<br/> '. $pue. 
' <br/> '; 
$PRD = $rsa->privdecrypt ($pue); Echo ' Private decrypt: '. 

Symmetric encryption algorithm

Symmetric encryption (also known as private key encryption) is the encryption and decryption algorithm that uses the same key to encrypt and decrypt. Sometimes called the traditional cipher algorithm, the encryption key can be inferred from the decryption key, while the decryption key can also be inferred from the encryption key. In most symmetric algorithms, the encryption key and encryption key is the same, so it is also called the secret key algorithm or the single key algorithm. It requires the sender and receiver to agree on a key before secure communication. The security of the symmetric algorithm relies on the key, and the disclosure of the key means that anyone can decrypt the message they send or receive, so the confidentiality of the key is critical to communication.

The common algorithms of symmetric encryption are: des algorithm, 3DES algorithm, Tdea algorithm, Blowfish algorithm, RC5 algorithm, Idea algorithm.

There are also encapsulated symmetric cryptographic functions in PHP

string UrlEncode (String $str)/ 
1. A parameter that passes in the string to be encrypted (usually applied to the encryption of the URL) 
2. UrlEncode for bidirectional encryption, which can be encrypted using urldecode (strictly speaking, not real encryption, more like a coding method) 
3. Returns a string in which all non-alphanumeric characters except-_ are replaced by a percent semicolon (% Followed by a two-bit hexadecimal number, and the space is encoded as a plus sign (+). 

Solve problems with & characters in links through the UrlEncode function:

$pre _url_encode= "Zhougang.com?username=zhougang&password=zhou";//In actual development, we often have to construct this URL, This is no problem 
$url _decode  = "Zhougang.com?username=zhou&gang&password=zhou";//But $_get in this case () To accept is going to be a problem; 
/* Array 
 [username] => Zhou 
 [gang] => 
 [password] => Zhou 
) */ 
/ Solve the problem as follows: 
$username = "Zhou&gang"; 
$url _decode= "Zhougang.com?username=". UrlEncode ($username). &password=zhou "; 
? > 
Common UrlEncode () conversion characters 
?  =>%3f 
= =>%3d 
% =>%25 
& =>%26 
\ =>%5c 
string Base64_decode ( String $encoded _data) 
  Base64_encode () accepts a parameter, which is the data to be encoded (here does not say string, because many times base64 is used to encode pictures) 
  Base64_encode () For bidirectional encryption, Base64_decode () can be used to decrypt the 
$data =file_get_contents ($filename); 
echo Base64_encode ($data); 
/* Then you look at the page source will get a large string of base64 strings, and 
then use Base64_decode () restore can get pictures. This can also be used as one of the solutions for uploading pictures on the mobile side (but not recommended) 
* * * *


Strictly speaking. These two functions are not really encryption, more like a serialization of a format

The following are the symmetric cryptographic algorithms commonly used in our PHP programs

Discuz Classical algorithm

<?php function Authcode ($string, $operation = ' DECODE ', $key = ', $expiry = 0) {//dynamic key length, the same plaintext will generate different ciphertext is depending on the dynamic key  
  $ckey _length = 4;  
  Key $key = MD5 ($key $key: $GLOBALS [' Discuz_auth_key ']);  
  Key A will participate in the encryption and decryption $keya = MD5 (substr ($key, 0, 16));  
  Key B is used to do data integrity validation $keyb = MD5 (substr ($key, 16, 16)); Key C used to change the generated ciphertext $KEYC = $ckey _length?  
  ($operation = = ' DECODE ' substr ($string, 0, $ckey _length): substr (MD5 (Microtime ()),-$ckey _length)): ";  
  The key $cryptkey = $keya. MD5 ($keya. $KEYC) that participate in the operation;  
  $key _length = strlen ($cryptkey); PlainText, the first 10 bits to save the timestamp, verify the validity of the data when decrypting, 10 to 26 bits to save the $KEYB (key B),//decryption will verify the data integrity through this key///If it is decoded, it will start from the first $ckey_length, because the ciphertext before $ckey_ The length bit holds the dynamic key to ensure the decryption is correct $string = $operation = = ' DECODE '? Base64_decode (substr ($string, $ckey _length)): sprintf ('%010d ', $expiry? $expiry + Time (): 0). substr (MD5 ($string. $keyb  
  , 0). $string;  
  $string _length = strlen ($string);  
  $result = ';  
  $box = Range (0, 255); $rndkey = ARray ();  
  Generate the key book for ($i = 0; $i <= 255 $i + +) {$rndkey [$i] = Ord ($cryptkey [$i% $key _length]); //using fixed algorithm to disrupt the key book, increase randomness, it seems very complex, in fact, will not increase the intensity of the ciphertext for ($j = $i = 0; $i < 256 $i + +) {$j = ($j + $box [$i] + $rn  
    dkey[$i])% 256;  
    $tmp = $box [$i];  
    $box [$i] = $box [$j];  
  $box [$j] = $tmp;  
    }//Core 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 is derived from the key book, and then converted to the character $result. = Chr (ord ($string [$i]) ^ ($box [($box [$a] + $box [$j]) (% 256])); } if ($operation = = ' DECODE ') {//Validate data validity, see unencrypted plaintext format if (substr ($result, 0,) = 0 | | substr ($result, 0, -time () > 0) && substr ($result) = = substr (MD5 (substr ($result,). $keyb), 0) {retur  
    n substr ($result, 26);  
    else {return '; } else {//Keep the dynamic key in the ciphertext, which is whyThe same clear text, the production of different ciphertext can be decrypted after the reason//because the encrypted ciphertext may be some special characters, the copy process may be lost, so use base64 code return $KEYC. Str_replace (' = ', ', base64_encod  
  E ($result)); 

Add decryption function encrypt ()

<?php//$string: Need to encrypt the decrypted string; $operation: To determine whether to encrypt or decrypt, E to encrypt, d to decrypt; $key: Key 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 ($res 
    }else{return "; }}else{return Str_replace(' = ', ', ' Base64_encode ($result)); 

Thank you for reading, I hope to help you, thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.