Several methods to implement encryption in PHP _ PHP Tutorial

Source: Internet
Author: User
Tags crypt form post md5 hash printable characters rounds sha1 encryption alphanumeric characters
Several methods to implement encryption in PHP are introduced. Several methods for implementing encryption in PHP this article mainly introduces several methods for implementing encryption in PHP, which are very comprehensive and practical and are frequently used in projects, for more information about how to implement encryption in PHP, see

This article mainly introduces several PHP encryption methods, which are very comprehensive and practical, and are frequently used in projects. For more information, see

There are several encryption methods 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, the MD5 message digest is returned in the original binary format of 16 bytes.

This is irreversible encryption. execute the following code:

$ Password = '000000 ';
Echo md5 ($ password );
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 alternative algorithms available on the system.

Parameters

Str -- string to be hashed.

Salt -- optional salt value string. If it is not provided, the algorithm behavior will be determined by different algorithms and may lead to an unpredictable end.

This is also an irreversible encryption method. execute the following code:

The code is as follows:


$ Password = '000000 ';
$ Salt = "test"; // only the first two
Echo crypt ($ password, $ salt );

The result is teMGKvBPcptKo.

An example of using an automatic salt value is as follows:

The code is as follows:


$ Password = crypt ('mypassword'); // automatically generate a salt value
/* You should use the complete result obtained by crypt () as the salt value for password verification to avoid problems caused by different hash algorithms. (As described above, the password hash based on the standard DES algorithm uses a 2-character salt value, but the MD5 algorithm uses a 12-character salt value .) */
If (crypt ('mypassword', $ password) = $ password ){
Echo "Password verified! ";
}

The execution result is output Password verified!

The example of using crypt () with different hash types is as follows:

The code is 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 = 1 ){
Echo 'blowfish: '. crypt ('rasmuslerdorf',' $ 2a $07 $ usesomesillystringforsalt $ '). "\ n ";
}
If (CRYPT_SHA256 = 1 ){
Echo 'Sha-256: '. crypt ('rasmuslerdorf',' $5 $ rounds = 5000 $ usesomesillystringforsalt $ '). "\ n ";
}
If (CRYPT_SHA512 = 1 ){
Echo 'Sha-512: '. crypt ('rasmuslerdorf',' $6 $ rounds = 5000 $ usesomesillystringforsalt $ '). "\ n ";
}

The result is as follows:

Standard DES: rl.3StKT. 4T8M
Extended DES: _ j9.. rasmBYk8r9AiWNc
MD5: $1 $ rasmusle $ rISCgZzpwk3UhDidwXvin0
Blowfish: $ 2a $07 $ usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256: $5 $ rounds = 5000 $ usesomesillystri $ kq?panxzhkq2bob43tsayhewsq1lr5qnypcdh/Tp.6
SHA-512: $6 $ rounds = 5000 $ usesomesillystri $ Forbidden. S5KPgErtP/EN5mcO. ChWQW21
In a system where the crypt () function supports multiple hashes, the following constants are set to 0 or 1 based on whether the corresponding types are available:

CRYPT_STD_DES-the hash based on the standard DES algorithm uses two characters in the "./0-9A-Za-z" character as the salt value. Using invalid characters in the salt value causes crypt () to fail.
CRYPT_EXT_DES-extended DES-based hash. The salt value is a 9-character string consisting of a 4-byte loop followed by an underscore and a 4-byte salt value. They are encoded into printable characters, each of which has 6 characters, with the least valid characters given priority. 0 to 63 are encoded as "./0-9A-Za-z ". Using invalid characters in the salt value causes crypt () to fail.
CRYPT_MD5-MD5 hash uses a 12-character string salt value starting with $1 $.
The CRYPT_BLOWFISH-Blowfish algorithm uses the following salt value: "$ 2a $", a two-digit cost parameter, "$", and a 64-bit string consisting of characters in "./0-9A-Za-z. Using a character out of this range in the salt value causes crypt () to return an empty string. The two cost parameters are the base 2 logarithm of the number of loops, and the value range is 04-31. exceeding this range will cause crypt () to fail.
CRYPT_SHA256-the SHA-256 algorithm uses a 16-character string salt value starting with $5 $ for hash. If the salt value string is "rounds = Starting with $, the number of N is used to specify the number of execution times of the hash loop, which is similar to 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 out of this range will be converted to the nearest value.
CRYPT_SHA512-the SHA-512 algorithm hashes salt values from a 16-character string starting with $6 $. If the salt value string is "rounds = Starting with $, the number of N is used to specify the number of execution times of the hash loop, which is similar to 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 out of 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 characters; otherwise, the return value is a hexadecimal number of 40 characters.

This is also an irreversible encryption method. execute the following code:

$ Password = '000000 ';
Echo sha1 ($ password );
The result is 7c4a8d09ca3762af61e59520943dc26494f8941b.

Although the preceding methods are irreversible, they can be decrypted by dictionary lookup. The following address provides the ability to decrypt the above encryption results.

Http://www.cmd5.com/

If you add a password, it will be useless. otherwise, as long as your encryption is complex enough, the less likely it will be to be cracked, for example, if the above three encryption methods are used for hybrid encryption, I will recommend you to use a php encryption library.

4. URL encryption

String urlencode (string $ str)

This function allows you to encode a string and use it in the URL request section. It also allows you to pass variables to the next page.

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

String urldecode (string $ str)

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

This is reversible encryption. The urlencode method is used for encryption and the urldecode method is used for decryption. run the following code:

$ Url = 'http: // www.xxx.com/craryprimitiveman /';
$ EncodeUrl = urlencode ($ url );
Echo $ encodeUrl. "\ n"; // if it is displayed on a webpage, change \ n

Echo urldecode ($ encodeUrl );
The result is as follows:

Http % 3A % 2F % 2Fwww.xxx.com % 2 FCraryPrimitiveMan % 2F
Http://www.xxx.com/CraryPrimitiveMan/
The following describes how to encrypt a URL based on RFC 3986:

The code 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 ');
$ Replacements = array ('! ',' * ', "'", "(", ")", ";", ":", "@", "&", "= ", "+", "$ ",",","/","? "," % "," # "," [","] ");
Return str_replace ($ entities, $ replacements, urlencode ($ string ));
}

5. Base64 information encryption

String base64_encode (string $ data)

Use base64 to encode data.

This encoding is designed to enable binary data to be transmitted through a non-pure 8-bit transport layer, such as the subject of an email.

Base64-encoded data takes up about 33% more space than raw data.

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

Decodes base64-encoded data.

Parameters

Data-encoded data.

Strict -- if the input data exceeds the base64 alphabet, FALSE is returned.

Run the following code:

The code is as follows:


$ Name = 'craryprimitiveman ';
$ EncodeName = base64_encode ($ name );
Echo $ encodeName. "\ n ";
Echo base64_decode ($ encodeName );

The result is as follows:

The code is as follows:


Q3JhcnlQcmltaXRpdmVNYW4 =
CraryPrimitiveMan

Recommended phpass

According to the phpass 0.3 test, a standard hash method is used to protect the user password before it is stored in the database. Many common hash algorithms, such as md5 and even sha1, are insecure for password storage, because hackers can use these algorithms to easily crack passwords.

The most secure way to hash passwords is to use the bcrypt algorithm. The open-source phpass Library provides this function with an easy-to-use class.

The code is as follows:


// Include phpass Library
Require_once ('phpass-03/PasswordHash. php ')
// Initialize the hash to be unportable (this is safer)
$ Hasher = new PasswordHash (8, false );
// Calculate the hash value of the password. $ HashedPassword is a string of 60 characters.
$ HashedPassword = $ hasher-> HashPassword ('My super cool password ');
// You can safely save $ hashedPassword to the database now!
// Compare the user input content (generated hash value) with the previously calculated hash value to determine whether the user has entered the correct password
$ Hasher-> CheckPassword ('the wrong password', $ hashedPassword); // false
$ Hasher-> CheckPassword ('My super cool password', $ hashedPassword); // true
?>

The above is an introduction to PHP encryption. I hope you will like it.

Ghost This article mainly introduces several PHP encryption methods, which are very comprehensive and practical. they are often used in projects. if you need them, you can refer to them...

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.