A brief talk on various encryption techniques and code examples in PHP

Source: Internet
Author: User
Tags crypt decrypt md5 encryption md5 hash ord urlencode alphanumeric characters asymmetric encryption

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 ');

sdvaIs 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 each time the refresh is changed */echo "
SHA1 Encryption:
String SHA1 (String $str [, bool $raw _output = false]); Like MD5, the difference is SHA1 () returns a hash value of 40 characters by default, passing in a parameter, the first is an encrypted string, the second is a Boolean value of Raw_output, the default is False, and if set to TRUE,SHA1 () returns the original 20 <?php$my_intro= "Zhouxiaogang" in the original format, Echo SHA1 ($my _intro); B6773e8c180c693d9f875bcf77c1202a243e8594echo "
Asymmetric encryption

The asymmetric encryption algorithm requires two keys for encryption and decryption, both of which are the public key (publicly key, the public key) and the private key, or the secret key (private key);

, the secure transmission of important information is accomplished by using asymmetric encryption between A and B.

    1. Party B generates a pair of keys (public and private) and exposes the public key to other parties.
    2. The party that obtains the public key uses the key to encrypt the confidential information before sending it to party B.
    3. 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.

In the transmission process, even if the attacker intercepts the transmitted ciphertext and obtains the public key of B, the cipher cannot be cracked, because only the private key of B can decrypt the text.
Similarly, if B to reply to the encrypted information to a, then need to publish a public key to B for encryption, a self-preservation of a private key for decryption.

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

Here is an 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 ($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; }/** * Decrypt with the private key */Public Function Privdecrypt ($encrypted) {if (!is_string ($enc        rypted)) {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); }}//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 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";// However, it is problematic to accept $_get () in this case;/*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)
    1. Base64_encode () accepts a parameter, which is the data to be encoded (not the string here, because many times base64 is used to encode the image)
    2. Base64_encode () is bidirectional encrypted and can be decrypted with Base64_decode ()
$data =file_get_contents ($filename); Echo Base64_encode ($data);/* and then you look at the Web page source will get a bunch of base64 string, 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
<?phpfunction 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 it is complex, actually does not increase the strength of the ciphertext for ($j = $i = 0; $i <; $i + +) {$j = ($j + $box [$           I] + $rndkey [$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) = = | | | substr ($R           Esult, 0, 16)-time () > 0) && substr ($result, 0, +) = = substr (MD5 (substr ($result,). $keyb)) {    Return substr ($result, 26);           } else {return ';           }} else {//To keep the dynamic key 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 copy process may be lost, so the base64 encoding       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 Su         BSTR ($result, 8); }else{            Return ';     }}else{return Str_replace (' = ', ' ', Base64_encode ($result)); }}?>

A brief discussion of various encryption techniques and code examples in PHP

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.