PHP Learning--php Encryption

Source: Internet
Author: User
Tags crypt form post md5 digest md5 hash printable characters rounds sha1 alphanumeric characters

There are several types of encryption in PHP:

1. MD5 Encryption

String MD5 (string $str [, bool $raw _output = false])

Parameters

STR--the original string.

Raw_output--If the optional raw_output is set to TRUE, then the MD5 Digest is returned in the original binary format of 16 bytes in length.

This is a non-reversible encryption, execute the following code

$password = ' 123456 ';  MD5 ($password);  

Get the result is e10adc3949ba59abbe56e057f20f883e

2. Crype Encryption

String crypt (String $str [, String $salt])

Crypt () returns a hash string based on the standard UNIX DES algorithm or other available alternative algorithms on the system.

Parameters

STR-the string to be hashed.

Salt--An optional string of salt values. If not provided, the algorithm behavior will be determined by the different algorithm implementations and may lead to an unpredictable end.

This is also an irreversible encryption, which executes the following code

$password = ' 123456 ';  $salt = "Test"; // only take the first two crypt ($salt);     

The result is Temgkvbpcptko.

Examples of using automatic salt values are as follows:

automatically generate salt /* You should use the full result obtained by crypt () as the salt value for password checking to avoid problems caused by using different hashing algorithms. (as mentioned above, the password hash based on the standard DES algorithm uses a 2-character salt value, but a hash based on the MD5 algorithm uses 12 character salt values.) )*/if ($passwordecho "Password verified!" ;}

The result of the execution is the output Password verified!

Examples of using crypt () in different hash types are as follows:

if (crypt_std_des = = 1) {Echo ' Standard DES: '.Crypt (' Rasmuslerdorf ', ' RL '). "\ n";}if (crypt_ext_des = = 1) {Echo ' Extended DES: '.Crypt (' Rasmuslerdorf ', ' _j9. Rasm '). "\ n";}if (crypt_md5 = = 1) {Echo ' MD5: '.Crypt (' Rasmuslerdorf ', ' $1$rasmusle$ '). "\ n"if (Crypt_blowfish = = 1echo ' Blowfish: '. crypt (' Rasmuslerdorf ', ' $2a$07$usesomesillystringforsalt$ '). "\ n" ;} if (crypt_sha256 = = 1crypt (' Rasmuslerdorf ', ' $5$rounds=5000$usesomesillystringforsalt$ '). "\ n" ;} if (crypt_sha512 = = 1crypt (' Rasmuslerdorf ', ' $6$rounds=5000$usesomesillystringforsalt$ '). "\ n"             

The results are as follows

Standard des:rl.3stkt.4t8mextended DES: _j9. RASMBYK8R9AIWNCMD5:          $1$rasmusle $riscgzzpwk3uhdidwxvin0blowfish:     $2a$07$ usesomesillystringfore2udlvp1ii2e./u9c8sbjqp8i90dh6hisha-: $5$rounds=5000$usesomesillystri$ KQJWPANXZHKQ2BOB43TSAYHEWSQ1LR5QNYPCDH/TP.6sha: $6$rounds=5000$usesomesillystri$ D4irlxatmp7rx3p3inaxbeoomnaihckrvqp22jz6ey47wc6bkroiuuuboov1i.s5kpgertp/en5mco.chwqw21    

On systems where the crypt () function supports multiple hashes, the following constants are set to 0 or 1 depending on whether the appropriate type is available:

    • Crypt_std_des-a hash based on the standard DES algorithm uses the two characters in the "./0-9a-za-z" character as the salt value. Using illegal characters in salt values will cause crypt () to fail.
    • Crypt_ext_des-Extended DES algorithm-based hashing. A string with a salt value of 9 characters, consisting of 1 underscores followed by 4-byte cycles and 4-byte salt values. They are encoded into printable characters, each character 6 bits, and the effective bit is the least preferred. 0 to 63 are encoded as "./0-9a-za-z". Using illegal characters in salt values will cause crypt () to fail.
    • The CRYPT_MD5-MD5 hash uses a string salt value of 12 characters starting with $1$.
    • The Crypt_blowfish-blowfish algorithm uses the following salt values: "$2a$", a two-bit cost parameter, "$", and a string of 64 bits that are combined by the characters in "./0-9a-za-z". Using a character outside of this range in the Salt value causes crypt () to return an empty string. The two-bit cost parameter is the logarithm of the number of cycles with a base of 2, and its range is 04-31, and exceeding this range will cause crypt () to fail.
    • The crypt_sha256-sha-256 algorithm uses a 16-character string salt value that begins with $5$ to hash. If the salt string begins with "rounds=<n>$", the numeric value of N is used to specify the number of executions of the hash loop, much like the cost parameter of the Blowfish algorithm. The default number of cycles is 5000, the minimum is 1000, and the maximum is 999,999,999. N that exceeds this range will be converted to the nearest value.
    • The crypt_sha512-sha-512 algorithm uses a 16-character string salt value that begins with $6$ to hash. If the salt string begins with "rounds=<n>$", the numeric value of N is used to specify the number of executions of the hash loop, much like the cost parameter of the Blowfish algorithm. The default number of cycles is 5000, the minimum is 1000, and the maximum is 999,999,999. N that exceeds this range will be converted to the nearest value.
3. SHA1 Encryption

String SHA1 (String $str [, bool $raw _output = false])

Parameters

STR--Input string.

Raw_output--If the optional raw_output parameter is set to TRUE, the SHA1 Digest is returned in the original format of 20-character length, otherwise the return value is a 40-character hexadecimal number.

This is also an irreversible encryption, which executes the following code:

$password = ' 123456 ';  SHA1 ($password);  

The result is 7c4a8d09ca3762af61e59520943dc26494f8941b.

Although the above are non-reversible encryption, but can also be based on the way to decrypt the dictionary. The following address provides the ability to decrypt the above encryption results.

http://www.cmd5.com/

That everyone is not added even if add a secret, also useless ah, actually, as long as your encryption is complex enough, the likelihood of being cracked is smaller, for example, with the above three encryption methods of hybrid encryption, I will recommend to everyone a PHP encryption library.

4. URL encryption

String UrlEncode (String $str)

This function makes it easy to encode a string and use it for the request part of the URL, and it also facilitates the passing of a variable to the next page.

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 (+). This encoding is the same as the WWW form POST data, and is encoded in the same way as the application/x-www-form-urlencoded media type. For historical reasons, this encoding differs from the RFC1738 encoding in that the space is encoded as a plus sign (+).

String UrlDecode (String $str)

Decodes any%## in the encoded string given. The plus sign (' + ') is decoded into a space character.

This is a reversible encryption, the UrlEncode method is used for encryption, the UrlDecode method is used for decryption, and the following code is executed:

$url = ' http://www.cnblogs.com/CraryPrimitiveMan/';  UrlEncode ($url);  $encodeUrl. "\ n"; // If it is displayed on the webpage, it will be modified to <br/>UrlDecode ($encodeUrl);        

The results are as follows

http%3a%2f%2fwww.cnblogs.com%2fcraryprimitiveman%2Fhttp://www.cnblogs.com/CraryPrimitiveMan/ 

The method for encrypting URLs based on RFC 3986 is as follows:

 function Myurlencode ( $string  $entities = array ('%21 ', '%2a ', '%27 ', '%28 ', '%29 ', ' %3b ', '%3a ', '%40 ', '%26 ', '%3d ', '%2b ', '%24 ', '%2c ', '%2f ', '%3f ', '%25 ', '%23 ', '%5b ', '%5d ' ); return str_replace ($ Entities,  $replacements, urlencode ( $string            
5. BASE64 Information encoded encryption

String Base64_encode (String $data)

Use base64 to encode data.

This encoding is designed so that binary data can be transmitted through a non-pure 8-bit transport layer, such as the body of an e-mail message.

base64-encoded data takes up about 33% more space than the original data.

String Base64_decode (String $data [, bool $strict = false])

Decodes the base64 encoded data.

Parameters

Data--encoded

Strict-Returns FALSE if the input data exceeds the Base64 alphabet.

Execute the following code:

$name = ' Craryprimitiveman ';  Base64_encode ($name);  $encodeName. "\ n";  Base64_decode ($encodeName);       

The results are as follows

q3jhcnlqcmltaxrpdmvnyw4=Craryprimitiveman
Recommended Phpass

The Phpass 0.3 test is a standard way of hashing the user's password before depositing it into the database. Many commonly used hashing algorithms, such as MD5, or even SHA1, are unsafe for password storage because hackers can easily hack passwords using those algorithms.

The safest way to hash a password is to use the bcrypt algorithm. The Open source Phpass library provides this functionality in an easy-to-use class.

<?Php//Include Phpass LibraryRequire_once (' phpass-03/passwordhash.php ')//Initialize the hash to be non-portable (this is more secure)$hasher =New PasswordHash (8,false); // Computes the hash value of the password. $hashedPassword is a string of 60 characters in length.  $hashedPassword =  $hasher->hashpassword (' My super Cool password ' ); // You can now safely save $hashedPassword to the database!// Determine if the user entered the correct password by comparing the user input (the resulting hash value) and our previously computed hash value  $hasher->checkpassword (' the Wrong password ',  $hashedPassword); // False $hasher Checkpassword (' My super cool password ',  $hashedPassword); // True?>        

Trap

    • Many resources may recommend that you "add salt" to your password before hashing. The idea is good, but Phpass has "added salt" to your password in the Hashpassword () function, which means you don't need to "add salt" yourself.

PHP Learning--php Encryption

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.