Several ways to implement encryption in PHP introduce _php techniques

Source: Internet
Author: User
Tags base64 crypt form post numeric numeric value printable characters urlencode alphanumeric characters

There are several ways to encrypt 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, MD5 Digest will return in its original binary format in 16-byte length.

This is an irreversible encryption that executes the following code

$password = ' 123456 ';
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 available alternative algorithms on the system.

Parameters

STR--The string to be hashed.

Salt-an optional salt-value string. If not provided, the algorithm behavior is determined by different algorithms and can result in unpredictable completion.

This is also an irreversible encryption that executes the following code

Copy Code code as follows:

$password = ' 123456 ';
$salt = "Test";//Only take the first two
Echo Crypt ($password, $salt);

The result is Temgkvbpcptko

Examples of using automatic salt values are as follows:

Copy Code code as follows:

$password = Crypt (' MyPassword '); Automatically generate salt values
/* You should use the full result of crypt () as the salt value for the password check, in order to avoid the use of different hashing algorithm caused by the problem. (as noted above, a cryptographic hash based on the standard DES algorithm uses a 2-character salt value, but a hash based on the MD5 algorithm uses a 12-character salt value.) )*/
if (Crypt (' MyPassword ', $password) = = $password) {
echo "Password verified!";
}

Execution result is output Password verified!

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

Copy Code code 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 results are 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$ KQJWPANXZHKQ2BOB43TSAYHEWSQ1LR5QNYPCDH/TP.6
sha-512:      $6$rounds=5000$ Usesomesillystri$d4irlxatmp7rx3p3inaxbeoomnaihckrvqp22jz6ey47wc6bkroiuuuboov1i.s5kpgertp/en5mco.chwqw21
In The crypt () function supports multiple hashes on a system where 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 two characters from 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 hash based on the DES algorithm. A 9-character string that consists of 1 underscores followed by a 4-byte loop and a 4-byte salt value. They are encoded into printable characters, 6 bits per character, and the least effective bit is preferred. 0 to 63 is 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 that starts with a $1$ of 12 characters.
The Crypt_blowfish-blowfish algorithm uses the following salt value: "$2a$", a two-bit cost parameter, "$" and a 64-bit string that is composed of characters in "./0-9a-za-z". Using a character outside this range in the salt value will cause crypt () to return an empty string. The two-bit cost parameter is the logarithm of the number of cycles to 2, and its range is 04-31, which will cause crypt () to fail.
The crypt_sha256-sha-256 algorithm hashes with a 16 character string salt value that begins with the $5$. If the salt value string begins with "rounds=<n>$", the numeric value of N will be used to specify the number of times the hash cycle is executed, much like the cost parameter of the Blowfish algorithm. The default number of loops is 5000, the smallest is 1000, and the maximum is 999,999,999. N that is outside this range will be converted to the nearest value.
The crypt_sha512-sha-512 algorithm hashes with a 16 character string salt value that begins with the $6$. If the salt value string begins with "rounds=<n>$", the numeric value of N will be used to specify the number of times the hash cycle is executed, much like the cost parameter of the Blowfish algorithm. The default number of loops is 5000, the smallest is 1000, and the maximum is 999,999,999. N that is outside 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 summary is returned in the original format of 20 character lengths, otherwise the return value is a hexadecimal digit of 40 character length.

This is also an irreversible encryption that executes the following code:

$password = ' 123456 ';
Echo SHA1 ($password);
The result is 7c4a8d09ca3762af61e59520943dc26494f8941b

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

http://www.cmd5.com/

That everyone is added even if added a secret, also useless ah, in fact, as long as your encryption is complex enough to be cracked out of the possibility of the smaller, for example, with the above three encryption methods mixed encryption, and then I will recommend to everyone a PHP encryption library.

4. URL encryption

String UrlEncode (String $str)

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

Returns a string, in addition to the-_ in this string. All non-alphanumeric characters are replaced with a percent sign (%) followed by a two-bit hexadecimal number, and the space is encoded as a plus (+). This encoding is the same encoding 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 to decrypt, and executes the following code:

$url = ' http://www.xxx.com/CraryPrimitiveMan/';
$ENCODEURL = UrlEncode ($url);
Echo $encodeUrl. "\ n";//if displayed on the Web page, change \ n to <br/>
echo UrlDecode ($ENCODEURL);
The results obtained are as follows

http%3a%2f%2fwww.xxx.com%2fcraryprimitiveman%2f
http://www.xxx.com/CraryPrimitiveMan/
The method for encrypting URLs based on RFC 3986 is as follows:

Copy Code code 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 Encoding Encryption

String Base64_encode (String $data)

The data is encoded using Base64.

This encoding is designed to enable binary data to be transmitted through a 8-bit transport layer, such as the body of an e-mail message.

base64-encoded data consumes 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:

Copy Code code as follows:

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

The results are as follows

Copy Code code as follows:

q3jhcnlqcmltaxrpdmvnyw4=
Craryprimitiveman

Recommended Phpass

After the Phpass 0.3 test, the standard way to hash the password to protect the user before depositing it in the database. Many commonly used hashing algorithms such as MD5 and even SHA1 are unsafe for password storage because hackers can easily crack 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.

Copy Code code as follows:

<?php
Include Phpass Library
Require_once (' phpass-03/passwordhash.php ')
Initialization of the hash is not portable (this is more secure)
$hasher = new PasswordHash (8, false);
Computes the hash value of the password. $hashedPassword is a string of 60 characters long.
$hashedPassword = $hasher->hashpassword (' I super cool password ');
You can now safely save the $hashedPassword to the database!
To determine whether the user entered the correct password by comparing the user input (resulting hash value) and the hash value we calculated before
$hasher->checkpassword (' The wrong password ', $hashedPassword); False
$hasher->checkpassword (' I super cool password ', $hashedPassword); True
?>

The above is the article on the PHP encryption method introduced, I hope you can enjoy.

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.