PHP Learning--php Encryption, PHP learning--php Encryption _php Tutorial

Source: Internet
Author: User
Tags crypt form post md5 digest md5 encryption printable characters rounds urlencode alphanumeric characters

PHP Learning--php Encryption, PHP learning--php encryption


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 '; Echo 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"; // take only the first two Echo Crypt ($password$salt);

The result is Temgkvbpcptko.

Examples of using automatic salt values are as follows:

$password Crypt // automatically generate salt values /* 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 (crypt$password$password)   { Echo "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 = = 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.4t8mextended DES: _j9. RASMBYK8R9AIWNCMD5:          $1$rasmusle $riscgzzpwk3uhdidwxvin0blowfish:     $2a$ $usesomesillystringfore 2udlvp1ii2e./U9c8sbjqp8i90dh6hisha-:      $5$rounds =  $usesomesillystri $kqjwpanxzhkq2bob43tsayhewsq1lr5qnypcdh/tp.6SHA-512 :      $6$rounds =$usesomesillystri $ D4irlxatmp7rx3p3inaxbeoomnaihckrvqp22jz6ey47wc6bkroiuuuboov1i.s5kpgertp/en5mco.chwqw21

On systems that support multiple hashes on the crypt () function, 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 value string begins with "rounds= $", 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 value string begins with "rounds= $", 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 '; Echo 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/'; $ENCODEURL UrlEncode ($url); Echo $encodeUrl . "\ n"; // if it is displayed on a webpage, it will be modified to
Echo 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) {    $entitiesarray('%21 ', '%2a ', '% ", '%28 ', '%29 ', '%3b ', '%3a ', '%40 ', '%26 ', '%3d ', '%2b ', '%24 ', '%2c ', '%2f ', '%3f ', '%25 ', '%23 ', '%5b ', '%5d '); c7/>$replacementsarray('! ', ' * ', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "? ", "%", "#", "[", "]");     return Str_replace ($entities$replacementsurlencode($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 '; $encodeName Base64_encode ($name); Echo $encodeName . "\ n"; Echo 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 library require_once(' phpass-03/passwordhash.php ')// Initialize the hash to be non-portable (this is more secure) $hasher New 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 the $hashedPassword to the database!//to determine if the user entered the correct password by comparing the user input (the resulting hash value) and the hash value we calculated earlier $hasher $hashedPassword);  // false $hasher $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.

Further reading

    • Phpass
    • Why using a MD5 or SHA hash password is not secure (Chinese)
    • How to securely store passwords

Password encryption for PHP?

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 get an encrypted password in the above code, in fact, the user name and password with the MD5 () method encryption!

PHP Text Encryption function

Give you a I commonly used, also meet your requirements, very useful oh. /**
* Using RC4 as the core algorithm, by encrypting or decrypting user information
* @param $string-Encrypt or decrypt the string
* @param $operation-decode decryption; ENCODE encryption
* @param $key-the key defaults to Authkey constants
* @return Return string
*/define (' AUTHKEY ', ' yl_chen ');
function Mooauthcode ($string, $operation = ' DECODE ', $key = ', $expiry = 0) {/**
* $ckey _length with the secret key length value 0-32;
* Add the random key, you can make the ciphertext no rules, even if the original and key exactly the same, the encryption results will be different each time, increase the difficulty of cracking.
* The greater the value, the greater the ciphertext change rule, the ciphertext changes = 16 $ckey _length
* When this value is 0 o'clock, the random key is not 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, (+). $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 + +) {
$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 ... remaining full text >>

http://www.bkjia.com/PHPjc/903171.html www.bkjia.com true http://www.bkjia.com/PHPjc/903171.html techarticle PHP Learning--php Encryption, PHP learning--php Encryption in PHP has the following several 1. MD5 Encrypted string MD5 (string $str [, bool $raw _output = false]) parameter str--Raw string ...

  • 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.