Home  >  Article  >  Backend Development  >  Introduction to several ways to implement encryption in PHP, several ways to implement encryption in PHP_PHP tutorial

Introduction to several ways to implement encryption in PHP, several ways to implement encryption in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:06:29777browse

Introduction to several ways to implement encryption in PHP, several ways to implement encryption in PHP

The encryption methods in PHP are as follows

1. MD5 encryption

string md5 ( string $str [, bool $raw_output = false ] )

Parameters

str -- Original string.

raw_output -- If the optional raw_output is set to TRUE, the MD5 message digest will be returned in raw binary format with a length of 16 bytes.

This is an irreversible encryption, execute the following code

$password = '123456';
echo md5($password);
The result is e10adc3949ba59abbe56e057f20f883e

2. Crype encryption
string crypt ( string $str [, string $salt ] )

crypt() Returns a hashed string based on the standard UNIX DES algorithm or another alternative algorithm available on the system.

Parameters

str -- The string to be hashed.

salt -- Optional salt value string. If not provided, algorithm behavior will be determined by different algorithm implementations and may lead to unpredictable endings.

This is also an irreversible encryption, execute the following code

Copy code The code is as follows:

$password = '123456';
$salt = "test"; // Only take the first two
echo crypt($password, $salt);

The result is teMGKvBPcptKo

An example of using automatic salt value is as follows:

Copy code The code is as follows:

$password = crypt('mypassword'); // Automatically generate salt value
/* You should use the complete result of crypt() as a salt value for password verification to avoid problems caused by using different hashing algorithms. (As mentioned above, password hashes based on the standard DES algorithm use a 2-character salt, but hashes based on the MD5 algorithm use a 12-character salt.) */
if (crypt('mypassword', $password) == $password) {
echo "Password verified!";
}

The execution result is the output Password verified!

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

Copy code 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 results are as follows

Standard DES: rl.3StKT.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:                                                                                                           Blowfish: $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256: $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512: $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
On systems where the crypt() function supports multi-hashing, the following constants are set to 0 or 1 depending on whether the corresponding type is available:

CRYPT_STD_DES - A hash based on the standard DES algorithm using two of the "./0-9A-Za-z" characters as the salt. Using illegal characters in the salt will cause crypt() to fail.

CRYPT_EXT_DES - Extended hashing based on the DES algorithm. The salt is a 9-character string consisting of an underscore followed by the 4-byte cycle count and the 4-byte salt. They are encoded into printable characters, 6 bits each, with the least significant bits first. 0 to 63 are encoded as "./0-9A-Za-z". Using illegal characters in the salt will cause crypt() to fail.
CRYPT_MD5 - MD5 hashing uses a 12-character string salt starting with $1$.
CRYPT_BLOWFISH - The Blowfish algorithm uses the following salt: "$2a$", a two-digit cost parameter, "$", and a 64-bit string consisting of characters from "./0-9A-Za-z". Using characters outside this range in the salt will cause crypt() to return an empty string. The two-digit cost parameter is the base-2 logarithm of the number of cycles. Its range is 04-31. Exceeding this range will cause crypt() to fail.
CRYPT_SHA256 - The SHA-256 algorithm hashes using a 16-character string salt starting with $5$. If the salt string begins with "rounds=$", the numeric value of N will be used to specify the number of hashing rounds to execute, much like the cost parameter of the Blowfish algorithm. The default number of loops is 5000, the minimum is 1000, and the maximum is 999,999,999. N outside this range will be converted to the nearest value.
CRYPT_SHA512 - The SHA-512 algorithm hashes using a 16-character string salt starting with $6$. If the salt string begins with "rounds=$", the numeric value of N will be used to specify the number of hashing rounds to execute, much like the cost parameter of the Blowfish algorithm. The default number of loops is 5000, the minimum is 1000, and the maximum is 999,999,999. N 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 digest will be returned in raw format with a length of 20 characters, otherwise the return value is a 40-character hexadecimal number.

This is also an irreversible encryption, execute the following code:

$password = '123456';

echo sha1($password);
The result obtained is 7c4a8d09ca3762af61e59520943dc26494f8941b

Although the above types are irreversible encryption, they can also be decrypted by looking up the dictionary. The following address provides the function to decrypt the above encryption result.

http://www.cmd5.com/

Do you think it is useless even if you add encryption? In fact, it is not the case. As long as your encryption is complex enough, the possibility of being cracked is smaller. For example, you can use a mixture of the above three encryption methods to encrypt. I will recommend to everyone a php encryption library.

4. URL encryption

string urlencode ( string $str )

This function facilitates encoding a string and using it in the request part of the URL, and it also facilitates passing variables to the next page.

Returns a string in which all non-alphanumeric characters except -_. will be replaced with a percent sign (%) followed by two hexadecimal digits, and spaces are encoded as plus signs ( +). This encoding is the same as the encoding of WWW form POST data, and the same encoding as the application/x-www-form-urlencoded media type. For historical reasons, this encoding differs from the RFC1738 encoding in encoding spaces as plus signs (+).

string urldecode ( string $str )

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

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

$url = 'http://www.xxx.com/CraryPrimitiveMan/';

$encodeUrl = urlencode($url);
echo $encodeUrl . "n";// If it is displayed on a web page, change n to

echo urldecode($encodeUrl);
The results obtained are as follows

http%3A%2F%2Fwww.xxx.com%2FCraryPrimitiveMan%2F

http://www.xxx.com/CraryPrimitiveMan/
The method of encrypting URLs based on RFC 3986 is as follows:

Copy code 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 encoding and encryption

string base64_encode ( string $data )

Encode data using base64.

This encoding is designed to enable binary data to be transmitted over non-pure 8-bit transport layers, such as the body of an email.

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

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

Decode base64 encoded data.

Parameters

data -- encoded data.

strict -- Returns FALSE if the input data exceeds the base64 alphabet.

Execute the following code:

Copy code The code is as follows:

$name = 'CraryPrimitiveMan';
$encodeName = base64_encode($name);
echo $encodeName . "n";
echo base64_decode($encodeName);

The results are as follows

Copy code The code is as follows:

Q3JhcnlQcmltaXRpdmVNYW4=
CraryPrimitiveMan

Recommend phpass

Tested with phpass 0.3, the standard way to protect user passwords by hashing them before storing them in the database. Many commonly used hashing algorithms such as md5 and even sha1 are not secure for password storage because hackers can easily crack passwords using those algorithms.

The most secure way to hash passwords is to use the bcrypt algorithm. The open source phpass library provides this functionality in an easy-to-use class.

Copy code The code is as follows:

// Include phpass library
require_once('phpass-03/PasswordHash.php')
// Initialize the hasher to be non-portable (this is safer)
$hasher = new PasswordHash(8, false);
// Calculate the hash value of the password. $hashedPassword is a 60-character string.
$hashedPassword = $hasher->HashPassword('my super cool password');
// You can now safely save $hashedPassword to the database!
// Determine whether the user entered the correct password by comparing the user input content (generated hash value) with the hash value we calculated previously
$hasher->CheckPassword('the wrong password', $hashedPassword); // false
$hasher->CheckPassword('my super cool password', $hashedPassword); // true
?>

The above is the introduction of this article about PHP encryption method. I hope you will like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/959105.htmlTechArticleIntroduction to several ways to implement encryption in PHP. Several ways to implement encryption in PHP. The encryption methods in PHP are as follows 1 . MD5 encrypted string md5 ( string $str [, bool $raw_output = false ] ) Parameter str -...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn