Encryption function in PHP

zhaozj2021-02-16  87

Encryption function in PHP

Original text reprinted from: http://blog.9cbs.net/freebyu/archive/2004/07/30/56311.aspx

Preliminary knowledge? Before the security features of PHP, we need to take some time to introduce some readers who have not been exposed to this aspect. If the basic concept of cryptography is already very familiar, you can jump In the past part.

Cryptography can be easily described as a process and experiment of add / decryption. Encryption is a process of converting easy-to-understand data into unhabilitation data. Decryption is a process that will not be understood into the original easy-to-understand data. The information that is not easy to understand is called a password, and the information that is easy to understand is called a clear code.

Data add / decryption requires a certain algorithm, which can be very simple, such as the famous Caesar code, but the current encryption algorithm is much more complicated, some of which can be used to decipher by the existing method.

PHP encryption function? As long as some people who use non-Windows platform experience may be quite familiar with CRYPT (), this function completes the function called a single-way encryption, which can encrypt some codes, but cannot convert passwords to The original codes. Although it seems to be a function of nothing from the surface, it is indeed widely used to ensure the integrity of the system password. Because, one-way encrypted passwords have fallen into third-party people, because they cannot be reduced as plaintext, there is no big use. When verifying the password entered by the user, the user's input is also a one-way algorithm, and if the input is matched to the stored encrypted password, the inputed port letter must be correct.

PHP also provides the possibility of using its CRYPT () function to complete the one-way encryption function. I will briefly introduce this function here:

String crypt (String Input_String [, STRING SALT])? The input_string parameter is a string that needs to be encrypted. The second optional Salt is a bit string that can affect the encrypted dark code, further exclude Calculate the possibility of attack. By default, PHP uses a 2-character DES interference string, if your system uses MD5 (I will introduce the MD5 algorithm later), it will use a 12-character interference string. Let's talk about it, you can find the length of the interference string to be used by executing the following command:

Print "My System Salt Size IS:". Crypt_salt_length ;? The system may also support other encryption algorithms. Crypt () supports four algorithms, the following is the length of the algorithm it supports and the corresponding SALT parameters:

Algorithm SALT length? CRYPT_STD_DES 2-Character (default)? Crypt_ext_des 9-Character? Crypt_MD5 12-Character Beginning With $ 1 $? Crypt_blowfish 16-Character Beginning With $ 2 $ 2 $

User authentication with CRYPT () As an example of the Crypt () function, consider such a case, you want to create a PHP script limit to a directory access, only allowing users to provide the correct username and password access This directory. I will store the information in a table I like database MySQL. Below we start our examples to create this table called Members:

MySQL> CREATE TABLE MEMBERS (? -> Username Char (14) Not null ,? -> Password Char (32) Not null ,? -> PRIMARY Key (username)? ->)

Then we assume that the following data has been stored in this table:

Username Password? Clark Kelod1c377lke? Bruce Ba17vnz9awgk? Peter Paluvrwsrlz4u These encrypted passwords correspond to Kent, Banner, and Parker, respectively. Pay attention to the first two letters per password, because I use the following code, create an interference string according to the first two letters of the password:

$ ENTEREDPASSWORD.? $ SALT = SUBSTR ($ EnteredPassword, 0, 2); $ Userpswd = Crypt ($ EnteredPassword, $ Salt) ;? // $ USERPSWD then stored with the username in MySQL

I will use Apache's password-Answer authentication configuration prompting users to enter username and password, a freshly known information about PHP information is, it can identify user names and password entered by Apache to $ PHP_AUTH_USER and $ PHP_AUTH_PW, I will use these two variables in the authentication script. Take some time carefully read the following scripts, pay more attention to the explanation of it, in order to better understand the following code:

Crypt () and Apache password - response verification system application?

$ host = "localhost"; $ user = "zorro"; $ pswd = "hellodolly"; $ db = "users";

// set Authorization to False

$ authorization = 0;

// Verify That User Has Entered UserName and Password

IF (Isset ($ PHP_AUTH_USER) && isset ($ PHP_AUTH_PW):

Mysql_pconnect ($ Host, $ USER, $ PSWD) or Die ("Can't connect to mysql?");

mysql_select_db ($ db) or Die ("Can't SELECT DATABASE!");

// Perform the Encryption? $ SALT = Substr ($ PHP_AUTH_PW, 0, 2); $ Encrypted_Pswd = Crypt ($ PHP_AUTH_PW, $ SALT);

// build the query

$ query = "SELECT Username from membrate where? username = '$ PASWORD =' $ encrypted_pswd '";

// Execute the query

IF (mysql_numrows) == 1):? $ authorization = 1 ;? Endif;

Endif;

// Confirm Authorization

IF ($ authorization):

Header ('www-authenticate: Basic realm = "private") ;? header (' http / 1.0 401 unauthorized ") ;? print" you are unauthorized to enter this area. ";

Else:

Print "this is the secret data!";

Endif;

?>

The above is a simple authentication system that verifies user access rights. When using CRYPT () protects important confidential information, remember that Crypt () used in the default state is not the safest, and can only be used in a system with lower security requirements, if a higher security is required Performance requires me to introduce the algorithm described later in this article. Below I will introduce another PHP support function ━━md5 (), this function uses the MD5 hash algorithm, which is a very interesting usage worth mentioning:

Mixed? A mixed function can convert a variable length information to have a fixed length that is mixed, and is also referred to as "information". This is very useful because a fixed length string can be used to check the integrity of the file and verify digital signatures and user authentication. Since it is suitable for PHP, the PHP built-in MD5 () mixed function will convert a variable length information to 128-bit (32 characters) information. One interesting feature of mixing is that it is not possible to get the original clear code by analyzing the mixed information, because the result of mixed results is not dependent on the original clear content. Even if only one character in a string is changed, the MD5 mixed algorithm will also calculate two distinct results. Let's first look at the contents of the table below and its corresponding results:

• Use the MD5 () mixed string?

$ msg = "this is some message"; $ enc_msg = md5 ($ msg) ;? Print "Hash: $ ENC_MSG";?>>

result:

Hash: 81EA092649CA32B5BA375E81D8F4972C? Note that the result is 32 characters. Let's take a look at the table below, where the value of $ msg has a little change:

Use MD5 () to mix a slightly changeful string?

? // Note that there is less in Message $ msg = "this is some mesage"; $ enc_msg = MD5 ($ msg) ;? Print "Hash2: $ ENC_MSG";??>

result:

Hash2: E86CF511BD5490D46D5CD61738C82C0C? It can be found that although the length of the two results is 32 characters, a little change in the clear text makes a significant change, and therefore, the mixed and MD5 () function is a small change in the data. A good tool.

Although Crypt () and MD5 () are useful, both are functionally limited. In the following section, we will introduce two very useful PHP extensions called Mcrypt and Mhash, which will greatly expand PHP users in encryption.

Although we explained the importance of unidirectional encryption in the above section, sometimes we may need to restore the password data into the original data after encryption, and the PHP provides this in the form of the Mcrypt expansion library. possibility.

McRYPT? Mcrypt 2.5.7 Unix | Win32? Mcrypt 2.4.7 is a powerful encryption algorithm expansion library, which includes 22 algorithms, including the following algorithms:

Blowfish RC2 Safer-sk64 xtea Cast-256 RC4 Safer-sk128 DES RC4-iv Serpent Enigma Rijndael-128 Threeway Gost Rijndael-192 TripleDES LOKI97 Rijndael-256 Twofish PanamaSaferplus Wake installation:???????? In the standard PHP software Do not include Mcrypt in the package, so you need to download it, the downloaded address is: ftp://argeas.cs-net.gr/pub/unix/mcrypt/. After downloading, compile according to the following method and expand it in PHP: Download the Mcrypt package. Gunzipmcrypt-xxxtar.gz? tar -xvfmcrypt-xxxtar? ./configure --disable-positall? cd to your php Directory.?............................................... - 中ot? make install? Of course, according to your requirements and PHP installation relationship with the Internet server software, the above process may need to make appropriate modifications.

The advantage of using Mcrypt? Mcrypt is more than just the encryption algorithm it provides, but it is also that it can add / decrypt the data, in addition, it provides 35 functions for processing data. Although the detailed introduction to these functions has exceeded the scope of this article, I still have to make a brief introduction on several typical functions.

First, I will introduce how to encrypt the data using the Mcrypt extension library, and then describe how to use it to decrypt. The following code is demonstrated on this process, first of all, encrypts the data, then displays the encrypted data on the browser, and restores the encrypted data to the original string, display it on the browser.

Use mcrypt to add, decrypt data?

// designate string to be encrypted? $ String = "Applied Cryptography, by Bruce Schneier, IS? A Wonderful Cryptography Reference."

// Encryption / decryption key? $ Key = "four score and twenty years ago";

// Encryption algorithm? $ Cipher_alg = mcrypt_rijndael_128;

// CREATE The Initialization Vector for Added Security.? $ IV = mcrypt_create_iv (mcrypt_get_iv_size ($ cipher_alg ,? mcrypt_mode_ecb), mcrypt_rand;

// Output Original String? Print "Original String: $ String

"

// Encrypt $ String? $ Encrypted_string = mcrypt_encrypt ($ Cipher_alg, $ Key, $ String, Mcrypt_Mode_CBC, $ IV);

// Convert to Hexadecimal and output to browser? Print "encrypted string:" .bin2hex ($ encrypted_string). "

"

$ decrypted_string = mcrypt_decrypt ($ CIPHER_ALG, $ Key, $ Encrypted_String, Mcrypt_Mode_CBC, $ IV); Print "Decrypted String: $ Decrypted_String";

?>

Executing the above script will produce the following output:

Original String: Applied Cryptography, by Bruce Schneier, IS A Wonderful Cryptography? Reference.

Encrypted string: 02a7c58b1ebd22a9523468694b091e60411cc4dea8652bb8072 34fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b c89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 bfbab5e?

Decrypted string: Applied Cryptography, by Bruce Schneier, IS A Wonderful Cryptography? Reference.

Two most typical functions in the upper code are mcrypt_encrypt () and mcrypt_decrypt (), and their use is obvious. I used the "Telegraph Password" mode, Mcrypt provides several encryption methods, and since each encryption method can affect password security specific characters, each mode needs to be understood. For readers who have not contacted password systems, it may be more interested in mcrypt_create_iv () functions, although thorough explanation for this function has exceeded the scope of this article, but I will still mention the initialization vector it created. (HENCE,? IV), this vector can make each message independent of each other. Although this initialization variable is required not all modes, the PHP will give a warning message if this variable is provided in the required mode.

Mhash extension? Http://sourceforge.net/projects/mhash/

The Mhash extension of the 0.8.3 version supports 12 mixed algorithms, carefully checks the header file Mhash.h of Mhash V.0.8.3, which supports the following mixed algorithm:

CRC32 HAVAL160 MD5? CRC32B HAVAL192 RIPEMD160? GOST HAVAL224 SHA1? HAVAL128 HAVAL256 TIGER? Installation • Like Mcrypt, Mhash is not included in the PHP package. For non-Windows users, the following is the installation process:

Download Mhash Extension Library? Gunzipmhash-x.x.x.tar.gz? Tar -xvfmhash-x.x.x.tar? ./Configure? Make? Make install? Cd

?/configure -with-mhash = [DIR] [- other-configuration-directives]]]

? make

Make Install

• Like Mcrypt, according to the installation of the PHP on the Internet server software, you may need to other configurations on Mhash.

For Windows users, there is a good PHP package including the Mhash extension library. Just download and decompress, then install it according to the instructions in the readme.first document.

Using Mhash? Mix the information is very simple, look at the following example:

? $ Hash_alg = MHASH_TIGER ;? $ message = "These are the directions to the secret fort. Two steps left,? Three steps right, and cha chacha." ;? $ hashed_message = mhash ($ hash_alg, $ message) ;? print "The hashed message is". Bin2hex ($ hashed_message); "Executing this section of the script will get the following output results:

The Hashed Message IS 07A92A4DB3A4177F19EC9034AE5400EB60D1A9FBB4ADE461? The purpose of using bin2HEX () is convenient for us to understand $ hashed_message output, because the result of mixing is a binary format, in order to convert it into an easy-to-understand format, it must be converted For hexadecimal format.

It should be noted that mixed is a one-way function, and the result is not dependent on input, so this information can be displayed. This strategy is usually used to allow users to compare files provided by download files and system administrators to ensure the integrity of the file.

Mhash has other useful functions. For example, I need to output a name of the algorithm supported by Mhash, because the names of all algorithms supported by Mhash are starting with Mhash_, so they can complete this task by executing the following code:

$ hash_alg = mhash_tiger ;? Print "this data has been hashed with the" .MHASH_GET_HASH_NAME ($ hashed_message). "Hashing? Algorithm.";?>

The resulting output is:

THIS DATA HASHINGORITHM. Is not safe! PHP is a server-side technology that cannot prevent data from being leaked during transmission. Therefore, if you want to implement a complete secure application, it is recommended to use Apache-SSL or other security server arrangements.

Conclusion? This article introduces one of the most useful features of PHP. Mcrypt and Mhash. In this article, I need to point out that a real secure PHP application should also include a secure server, because PHP is a server-side technology, so when the data is transmitted by the client to the server, it cannot Guarantee the security of the data. ? Author: Liu Yanqing

Posted on 2004 07

转载请注明原文地址:https://www.9cbs.com/read-11899.html

New Post(0)