PHP learning-PHP encryption, PHP learning-PHP Encryption
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 = '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 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:
$ Password = '000000'; $ salt = "test"; // obtain only the first two echo crypt ($ password, $ salt );
The result is teMGKvBPcptKo.
An example of using an automatic salt value is as follows:
$ Password = crypt ('mypassword'); // automatically generate the 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:
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.4T8MExtended DES: _J9..rasmBYk8r9AiWNcMD5: $1$rasmusle$rISCgZzpwk3UhDidwXvin0Blowfish: $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hiSHA-256: $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6SHA-512: $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.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 starts with "rounds = <N >$", the numeric value of N is used to specify the number of times hash loops are executed, 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 starts with "rounds = <N >$", the numeric value of N is used to specify the number of times hash loops are executed, 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 = '123456';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.cnblogs.com/craryprimitiveman/'{}encodeurl = urlencode ($ url); echo $ encodeUrl. "\ n"; // if it is displayed on a webpage, change \ n to <br/> echo urldecode ($ encodeUrl );
The result is as follows:
http%3A%2F%2Fwww.cnblogs.com%2FCraryPrimitiveMan%2Fhttp://www.cnblogs.com/CraryPrimitiveMan/
The following describes how to encrypt a URL Based on RFC 3986:
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:
$name = 'CraryPrimitiveMan';$encodeName = base64_encode($name);echo $encodeName . "\n";echo base64_decode($encodeName);
The result 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.
<? Php // Include phpass library require_once ('phpass-03/PasswordHash. php ') // initialize the hash to be unportable (which 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 save $ hashedPassword to the database safely 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?>
Traps
- Many resources may recommend that you add salt to your password before hashing ". The idea is good, but phpass has already added salt to your password in the HashPassword () function, which means you do not need to add salt yourself ".
Further reading
- Phpass
- Why is it insecure to use md5 or sha hash passwords (Chinese)
- How to securely store passwords
Php implements password encryption?
Function ChangeMsg (msgu, msgp)
{
If (msgu! = "" & Msgp! = "")
{
Delmsg = md5 (msgu );
Rname = substr (delmsg, 5, 1 ). ",". substr (delmsg, 7,1 ). ",". substr (delmsg, 15, 1 ). ",". substr (delmsg, 17,1 );
Rnamearray = explode (',', rname );
Rpass = md5 (msgp );
R_msg = str_replace (rnamearray, "", rpass );
} Else {
R_msg = msgp;
}
Return r_msg;
} You can obtain the encrypted password in the above Code, that is, the user name and password are encrypted using the md5 () method!
Php text encryption function
I will give you a common one that meets your requirements and is very easy to use. /**
* Uses RC4 as the core algorithm to encrypt or decrypt user information
* @ Param $ string-encrypted or decrypted string
* @ Param $ operation-DECODE decryption; ENCODE Encryption
* @ Param $ key-the default key is the AUTHKEY constant.
* @ Return returns a string.
*/Define ('authkey', 'yl _ chen ');
Function MooAuthCode ($ string, $ operation = 'decode', $ key = '', $ expiry = 0 ){/**
* $ Ckey_length random key length value: 0-32;
* Adding a random key makes the ciphertext irregular. Even if the original text and the key are identical, the encryption results will be different each time, increasing the difficulty of cracking.
* The larger the value, the larger the ciphertext change law. The ciphertext change is equal to the power of $ ckey_length of 16.
* If the value is 0, no random key is generated.
*/
$ Ckey_length = 4;
$ Key = md5 ($ key? $ Key: md5 (AUTHKEY. $ _ SERVER ['HTTP _ USER_AGENT ']);
$ Keya = md5 (substr ($ key, 0, 16 ));
$ Keyb = md5 (substr ($ key, 16, 16 ));
$ Keyc = $ ckey_length? ($ Operation = 'decode '? Substr ($ string, 0, $ ckey_length): substr (md5 (microtime (),-$ ckey_length): ''; $ cryptkey = $ keya. md5 ($ keya. $ keyc );
$ Key_length = strlen ($ cryptkey); $ string = $ operation = 'decode '? Base64_decode (substr ($ string, $ ckey_length): sprintf ('% 010d', $ expiry? $ Expiry + time (): 0). substr (md5 ($ string. $ keyb), 0, 16). $ string;
$ String_length = strlen ($ string); $ result = '';
$ Box = range (0,255); $ rndkey = array ();
For ($ I = 0; $ I <= 255; $ I ++ ){
$ Rndkey [$ I] = ord ($ cryptkey [$ I % $ key_length]);
} For ($ j = $ I = 0; I 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 ...... the remaining full text>