Multiple encryption techniques and code sample parsing in PHP

Source: Internet
Author: User
Symmetric encryption (also known as private key encryption) refers to encrypting and decrypting cryptographic algorithms that use the same key. Sometimes called a traditional cryptographic algorithm, the encryption key can be inferred from the decryption key, and the decryption key can also be inferred from the encryption key. In most symmetric algorithms, the encryption key and decryption key are the same, so the encryption algorithm is also called the secret key algorithm or single key algorithm.

classification of information encryption technology

Single hash encryption technology (irreversible encryption)

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

MD5

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

MD5 () is a one-way encryption, there is no reverse decryption algorithm, but still can be some common string through 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 at the time of registration I will randomly generate this string, and then through the above method to double encryption;

Crypt

It is rare to see someone using this function, if it is to be used in a symmetric or asymmetric algorithm, to understand both;

String crypt (String $str [, String $salt])//First is a string that needs to be encrypted, the second is a salt value (which is the encryption interference value, if not provided, it is automatically generated by PHP); Returns the hashed string or a string less than 13 characters. 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 changed once per refresh/echo "


Asymmetric Encryption

The Asymmetric encryption algorithm requires two keys for encryption and decryption, both public key (publicly key, short-public key) and private key (privately key, referred to as private key);



, the use of asymmetric encryption between A and B to complete the safe transmission of important information.

Party B generates a pair of keys (public and private) and exposes the public key to other parties.

The party that obtains the public key uses the key to encrypt the confidential information before sending it to party B.

Party B decrypts the encrypted information with another private key (private key) that it saves. Party B can only use its private key (private key) to decrypt the information encrypted by the corresponding public key.

During transmission, even if the attacker intercepts the transmitted ciphertext and obtains the public key of B, it is not possible to decipher the ciphertext because only the private key of B is able to decrypt the text

Similarly, if B is to reply to a cryptographic message, then a public key of a must be published first to encrypt it. A private key to save A is used for decryption. The main algorithms used by

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

The following is a excerpt from the Internet a PHP algorithm for asymmetric encryption via OpenSSL

<?php/** * Using OpenSSL for asymmetric encryption * @since 2010-07-08 */class Rsa {/** * private key */private $_privkey;   /** * 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 (empty Empty ($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 = OpenSSL     _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; }/** * DecryptWith the private key */Public Function Privdecrypt ($encrypted) {if (!is_string ($encrypted)) {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;     Public Function __destruct () {@fclose ($this->_privkey);   @fclose ($this->_pubkey); }}//The following is a simple test demo, if not required please delete $rsa = new RSA (' Ssl-key '); Private key encryption, public key decryption echo ' Source: I am the old turtle <br/> '; $pre = $rsa->privencrypt (' I am an 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: '. $PRD;?>

Symmetric encryption algorithm

Symmetric encryption (also known as private key encryption) refers to encrypting and decrypting cryptographic algorithms that use the same key. Sometimes called a traditional cryptographic algorithm, the encryption key can be inferred from the decryption key, and the decryption key can also be inferred from the encryption key. In most symmetric algorithms, the encryption key and decryption key are the same, so the encryption algorithm is also called the secret key algorithm or single key algorithm. It requires the sender and receiver to agree on a key before communicating securely. The security of a symmetric algorithm relies on the key, which means that anyone can decrypt the message they send or receive, so the confidentiality of the key is critical to the communication.

The common algorithms for symmetric encryption are: des algorithm, 3DES algorithm, Tdea algorithm, Blowfish algorithm, RC5 algorithm, Idea algorithm.
There is also a symmetric cryptographic function in PHP that is well encapsulated

Urlencode/urldecode 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 is two-way encryption, Can be encrypted with urldecode (strictly speaking, not real encryption, more like a coding method) 3. Returns a string, in addition to-_, in this string. All non-alphanumeric characters are replaced with a percent sign (%) followed by a two-digit hexadecimal number, and a space is encoded as a plus (+). */

Troubleshoot problems with & characters in links with the UrlEncode function:

<?php $pre _url_encode= "Zhougang.com?username=zhougang&password=zhou"; In actual development, we often have to construct this URL, which is no problem $url _decode  = "Zhougang.com?username=zhou&gang&password=zhou";// But in this case using $_get () to accept it will be problematic; /* 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 Base64  string Base64_decode (String $encoded _data)    Base64_encode () accepts a parameter, that is, the data to be encoded (not to mention the string here, because many times base64 is used to encode the picture)    Base64_encode () is two-way encryption, usable base64_decode () To decrypt  the $data =file_get_contents ($filename); Echo Base64_encode ($data);/* and then you look at the Web page source will get a bunch of base64 strings, and then use base64_ Decode () restore to get the picture. This can also be used as one of the processing options for uploading pictures on the mobile side (but not recommended) */?>

Strictly speaking. These two functions are not really encrypted, more like a serialization of a format
Here are the symmetric encryption algorithms commonly used in our PHP program
Discuz Classic algorithm

<?php function Authcode ($string, $operation = ' DECODE ', $key = ', $expiry = 0) {//dynamic key length, the same plaintext will generate different ciphertext is dependent 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 will be used for data integrity verification $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)): ";    Key to participate in the operation $cryptkey = $keya. MD5 ($keya. $KEYC);    $key _length = strlen ($cryptkey); PlainText, the first 10 bits are used to hold the timestamp, verify data validity when decrypting, 10 to 26 bits to save $keyb (key B),//decryption will verify data integrity through this key///If it is decoded, it will start from the $ckey_length bit, because the ciphertext before $ckey_ The length bit holds the dynamic key to ensure that 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 Key Book for ($i = 0; $i <= 255;    $i + +) {$rndkey [$i] = Ord ($cryptkey [$i% $key _length]); }//using a fixed algorithm to disrupt the key book, adding randomness, as if complex, actually does not increase the intensity of the ciphertext for ($j = $i = 0; $i < $i) {$j = ($j + $box [$i] + $rndke      y[$i])% 256;      $tmp = $box [$i];      $box [$i] = $box [$j];    $box [$j] = $tmp;      }//Core plus decryption section 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 into a character $result. = Chr (ord ($string [$i]) ^ ($box [($box [$a] + $box [$j])% 256]));  if ($operation = = ' DECODE ') {//Verify data validation, see the format of unencrypted plaintext if (substr ($result, 0, 0) = = 0 | | substr ($result, 10) -time () > 0) && substr ($result, ten, +) = = substr (MD5 ($result, $keyb), 0, +)) {return Sub      STR ($result, 26);      } else {return '; }} else {//The dynamic key is stored in the ciphertext, which is why the same plaintext, the production of different ciphertext can be decrypted after the reason//because the encrypted ciphertext may be some special characters, the copying process may be lost, theWith base64 code return $KEYC. Str_replace (' = ', ' ', Base64_encode ($result)); }  }

Add decryption function encrypt ()

<?php//$string: A string that requires encryption and decryption, $operation: Determines whether it is encrypted or decrypted, e means encryption, and d means decryption; $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 ($result     , 8);     }else{return ';   }}else{return Str_replace (' = ', ' ', Base64_encode ($result));}}?> 

The above is a variety of PHP encryption technology and code sample parsing content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.