Analysis of various encryption technologies and code samples in PHP, and php encryption code samples

Source: Internet
Author: User
Tags crypt md5 hash sha1 encryption alphanumeric characters asymmetric encryption

Analysis of various encryption technologies and code samples in PHP, and php encryption code samples

Symmetric encryption (also called private key encryption) refers to the encryption algorithm that uses the same key for encryption and decryption. It is also called the traditional cryptographic algorithm, that is, the encryption key can be derived from the decryption key, and the decryption key can also be derived from the encryption key. In most symmetric algorithms, the encryption key is the same as the decryption key. Therefore, this encryption algorithm is also called a private key algorithm or a single key algorithm.

Classification of Information Encryption technology

Individual hash encryption technology (irreversible encryption)

A Digest algorithm. It is not an encryption algorithm. It is a function used to change any long input string to a fixed long output string.

MD5

String md5 (string $ str [, bool $ raw_output = false]); // MD5 encryption, input any length string to return a unique 32-bit character

Md5 () is one-way encryption, and there is no reverse decryption algorithm. However, it can still be used to crack some common strings through methods such as collection, enumeration, and collision. In order to make it more troublesome to crack, therefore, we generally add a salt value (salt) and double MD5;

Md5 (md5 ($ password). 'sdva ');

Sdva is the salt value, and the salt value should be random. For example, md5 is often used in password encryption, so I will randomly generate this string during registration, then, use the above method to double encrypt it;

Crypt

This function is rarely used. If it is used, it may be used in symmetric or asymmetric algorithms;

String crypt (string $ str [, string $ salt]) // The first is the string to be encrypted, and the second is the salt value (encrypted interference value, is automatically generated by PHP by default); returns the hash 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. $ CQZ8I. ofeepKYrWp0oG8L1/* the eight characters between the second $ and the third $ are generated by PHP and changed once every refresh */echo "

Asymmetric encryption

Asymmetric encryption algorithms require two keys for encryption and decryption. These two keys are public keys and private keys );

, And implements safe transmission of important information through asymmetric encryption between Party A and Party B.

  • Party B generates a pair of keys (Public Key and private key) and discloses the public key to others.
  • Party A, who obtains the public key, uses the key to encrypt the confidential information and then sends it to Party B.
  • Party B then decrypts the encrypted information with another private key (Private Key. Party B can only use its 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 Party B, the ciphertext cannot be cracked because only Party B's private key can decrypt the ciphertext.

Similarly, if Party B wants to reply encrypted information to Party A, Party A needs to publish the public key of Party A to Party B for encryption, and Party A saves the private key of Party A for decryption.

The main algorithms used in asymmetric encryption include RSA, Elgamal, backpack algorithm, Rabin, D-H, and ECC. Among them, the most common algorithm is RSA.

The following is an asymmetric encryption algorithm for PHP extracted from the Internet using openssl.

<? Php/*** use 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 (emptyempty ($ 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 = op Enssl_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 ($ encrypted) {return null;} $ this-> setupPrivKey (); $ encrypted = base64_decode ($ encrypted); $ r = encrypt ($ 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, delete $ rsa = new Rsa ('ssl-key') if not required; // Private key Encryption and Public key decryption echo 'source: I am an old man <br/> '; $ pre = $ rsa-> pr IvEncrypt ('I am a newbie'); 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 called private key encryption) refers to the encryption algorithm that uses the same key for encryption and decryption. It is also called the traditional cryptographic algorithm, that is, the encryption key can be derived from the decryption key, and the decryption key can also be derived from the encryption key. In most symmetric algorithms, the encryption key is the same as the decryption key. Therefore, this encryption algorithm is also called a private key algorithm or a single key algorithm. It requires the sender and receiver to agree on a key before secure communication. The security of symmetric algorithms depends on keys. Leaking keys means that anyone can decrypt the messages they send or receive. Therefore, the confidentiality of keys is critical to communication.

Common symmetric encryption algorithms include DES, 3DES, TDEA, Blowfish, RC5, and IDEA.

There are also encapsulated symmetric encryption functions in PHP.

Urlencode/Urldecode string urlencode (string $ str)/* 1. A parameter that is used to pass in the string to be encrypted (usually used to encrypt the URL) 2. urlencode is bidirectional encryption and can be encrypted using urldecode (strictly speaking, it is not really encrypted, more like a encoding method. returns a string -_. all other non-alphanumeric characters will be replaced with a semicolon (%) followed by two hexadecimal numbers, and spaces will be encoded as the plus sign (+ ). */

Use the Urlencode function to solve the problem caused by the link containing & characters:

<? Php $ pre_url_encode = "zhougang.com? Username = zhougang & password = zhou "; // in actual development, we often need to construct this URL. This is no problem $ url_decode =" zhougang.com? Username = zhou & gang & password = zhou "; // However, in this case, using $ _ GET () for acceptance may cause problems; /* Array ([username] => zhou [gang] => [password] => zhou) * // solve the problem as follows: $ username = "zhou & gang "; $ url_decode = "zhougang.com? Username = ". urlencode ($ username)." & password = zhou ";?> What are the Conversion characters of common urlencode? ==>%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 base64 is often used to encode the image) base64_encode () is bidirectional encryption, which can be base64_decode () to decrypt $ data = file_get_contents ($ filename); echo base64_encode ($ data);/* then you can view the source code of the webpage to get a large string of base64, and then use base64_decode () restore to get the image. This can also be used as one of the processing solutions for uploading images to mobile terminals (but it is not recommended to do so) */?>

Strictly speaking, these two functions are not actually encrypted, but more like serialization in a format.

The following symmetric encryption algorithms are commonly used in PHP programs:

Discuz classic algorithm

<? Php function authcode ($ string, $ operation = 'decode', $ key = '', $ expiry = 0) {// dynamic key length, the same plaintext will generate different Ciphertext Based on the dynamic key $ ckey_length = 4; // key $ key = md5 ($ key? $ Key: $ GLOBALS ['discuz _ auth_key ']); // key a participates in encryption and decryption $ keya = md5 (substr ($ key, 0, 16 )); // key B is 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 )):''; // calculate the key $ cryptkey = $ keya. md5 ($ keya. $ keyc); $ key_length = strlen ($ cryptkey); // plaintext. The first 10 digits are used to save the timestamp. Data Validity is verified during decryption, 10 to 26 bits are used to save $ keyb (Key B). // This key is used for data integrity verification during decryption. // if the key is decoded, it starts from the $ ckey_length bit, because the $ ckey_length bit before the ciphertext stores the 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]);} // use a fixed algorithm to disrupt the key book and increase randomness. It seems complicated, in fact, the ciphertext strength is not added. 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 keys obtained from the key book are different or, then convert it into a character $ result. = chr (ord ($ string [$ I]) ^ ($ box [($ box [$ a] + $ box [$ j]) % 256]);} if ($ operation = 'decode') {// verify the data validity. See the unencrypted plaintext format 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 the ciphertext, this is also the reason why different ciphertext texts can be decrypted in the same plain text. // because the encrypted ciphertext may be special characters, the replication process may be lost, therefore, return $ keyc is encoded in base64 format. str_replace ('=', '', base64_encode ($ result ));}}

Encryption/Decryption function encrypt ()

<? Php // $ string: the string to be encrypted and decrypted; $ operation: determines whether the string is encrypted or decrypted. E Indicates encryption, and D indicates 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 = $ B Ox [$ 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,) = substr (md5 (substr ($ result, 8 ). $ key),) {return substr ($ result, 8) ;}else {return '';}} else {return str_replace ('= ','', base64_encode ($ result) ;}}?>

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

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.