search
HomeBackend DevelopmentPHP TutorialEncryption function of PHP security programming_PHP tutorial
Encryption function of PHP security programming_PHP tutorialJul 21, 2016 pm 04:09 PM
phpFunctionencryptionexiststatusSafetyusdataLifeprogrammingnetworkimportant


Data encryption has become increasingly important in our lives, especially given the large number of transactions that occur and the vast amounts of data that are transmitted over the Internet. If you are interested in adopting security measures, you will also be interested in learning about the series of security features provided by PHP. In this article, we'll introduce these features and provide some basic usage so that you can add security features to your applications. Preliminary knowledge Before introducing the security functions of PHP in detail, we need to take some time to introduce some basic knowledge about cryptography to readers who have not been exposed to this aspect. If you are already very familiar with the basic concepts of cryptography, you can skip this part. . Cryptozoology can be loosely described as the study and experiment of encryption/decryption. Encryption is the process of converting easy-to-understand data into incomprehensible data, and decryption is the process of converting incomprehensible data into original easy-to-understand data. Information that is difficult to understand is called a cipher, and information that is easy to understand is called a plaintext. Encryption/decryption of data requires certain algorithms. These algorithms can be very simple, such as the famous Caesar code, but current encryption algorithms are relatively more complex, and some of them are even undecipherable using existing methods. PHP encryption function Anyone who has a little experience using non-Windows platforms may be familiar with crypt(). This function performs a function called one-way encryption. It can encrypt some plain codes, but it cannot convert the password into the original plain code. Although this may seem like a useless feature on the surface, it is widely used to ensure the integrity of system passwords. Because once the one-way encrypted password falls into the hands of a third party, it cannot be restored to plain text, so it is of little use. When verifying the password entered by the user, the user's input also uses a one-way algorithm. If the input matches the stored encrypted password, the entered password must be correct. PHP also provides the possibility to complete one-way encryption using its crypt() function. I'll briefly describe the function here: string crypt (string input_string [, string salt]) The input_string parameter is the string that needs to be encrypted, and the second optional salt is a bit string that can affect the encrypted password, further ruling out the possibility of what is called a precomputation 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. By the way, you can discover the length of the interference string your system will use 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 are the algorithms it supports and the length of the corresponding salt parameter: algorithm Salt length CRYPT_STD_DES 2-character (Default) CRYPT_EXT_DES 9-character CRYPT_MD5 12-character beginning with 102/td> CRYPT_BLOWFISH 16-character beginning with 102/td> Implementing user authentication using crypt() As an example of the crypt() function, consider a situation where you want to create a PHP script to restrict access to a directory to only users who can provide the correct username and password. I will store the data in a table in MySQL, my favorite database. Let's start our example by creating the 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 is already stored in the table: username password clark keloD1C377lKE bruce ba1T7vnz9AWgk peter paLUvRWsRLZ4U The plain codes corresponding to these encrypted passwords are kent, banner and parker respectively. Pay attention to the first two letters of each password. This is because I used the following code to create the interference string based on the first two letters of the password: .
= substr(, 0, 2);
= crypt(, );
// Then it is stored in MySQL together with the user name I will use Apache's password-response authentication configuration to prompt the user for a username and password. A little known fact about PHP is that it can recognize the username and password entered by the Apache password-response system as and I will use the identity These two variables are used in the verification script.Take some time to read the script below carefully and pay more attention to the explanations to better understand the code below: Application of crypt() and Apache's password-response verification system
= "localhost";
= "zorro";
= "hellodolly";
= "users";

// Set authorization to False

= 0;

// Verify that user has entered username and password

if (isset() && isset()) :

mysql_pconnect (, , ) or die("Can't connect to MySQL
server!");

mysql_select_db() or die("Can't select database!");

// Perform the encryption
= substr(, 0, 2);
= crypt(, );

// Build the query

= "SELECT username FROM members WHERE
username = '' AND
password = ''";

// Execute the query

if (mysql_numrows(mysql_query()) == 1) :
= 1;
endif;

endif;

// confirm authorization

if (! ):

header('WWW-Authenticate: Basic realm="Private"');
header('HTTP/1.0 401 Unauthorized');
print "You are unauthorized to enter this area.";
exit;

else :

print "This is the secret data!";

endif;

?> The above is a simple authentication system to verify user access rights. When using crypt() to protect important confidential information, remember that crypt() used by default is not the most secure and can only be used in systems with lower security requirements. If higher security is required Performance requires the algorithm I introduce later in this article. Next I will introduce another function supported by PHP━━md5(). This function uses the MD5 hashing algorithm. It has several interesting uses worth mentioning: Mixed A hash function transforms a variable-length message into a fixed-length hashed output, also known as a "message digest".This is useful because a fixed-length string can be used to check file integrity and verify digital signatures and user authentication. As it is suitable for PHP, PHP's built-in md5() hash function will convert a variable-length message into a 128-bit (32-character) message digest. An interesting feature of mixed encoding is that the original plain code cannot be obtained by analyzing the mixed information, because the mixed result has no dependence on the original plain code content. Even changing only one character in a string will cause the MD5 hybrid algorithm to calculate two completely different results. Let’s first look at the contents of the following table and its corresponding results: Use md5() to mix strings = "This is some message that I just wrote";
= md5();
print "hash: ";
?> Result: hash: 81ea092649ca32b5ba375e81d8f4972c Note that the result is 32 characters long. Take a look at the following table again, where the values ​​have changed slightly: Use md5() to shuffle a slightly changed string //Note that there is one s missing in the message
= "This is some message that I just wrote";
= md5();
print "hash2:

";
?> Result: hash2: e86cf511bd5490d46d5cd61738c82c0c It can be found that although the length of both results is 32 characters, a small change in the plaintext causes a big change in the result. Therefore, the hashing and md5() functions are a good way to check small changes in the data. tools. Although crypt() and md5() have their uses, both are subject to certain limitations in functionality. In the following sections, we will introduce two very useful PHP extensions called Mcrypt and Mhash, which will greatly expand the encryption options for PHP users. Although we have explained the importance of one-way encryption in the above section, sometimes we may need to restore the password data to the original data after encryption. Fortunately, PHP provides this in the form of the Mcrypt extension library possibility. Mcrypt Mcrypt 2.5.7 Unix | Win32 Mcrypt 2.4.7 is a powerful encryption algorithm extension library. It 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 Install: Mcrypt is not included in the standard PHP software package, so you need to download it. The download address is: ftp://argeas.cs-net.gr/pub/unix/mcrypt/. After downloading, compile it as follows and extend it in PHP: Download the Mcrypt package. gunzipmcrypt-x.x.x.tar.gz tar -xvfmcrypt-x.x.x.tar ./configure --disable-posix-threads make make install cd to your PHP directory. ./configure -with-mcrypt=[dir] [--other-configuration-directives] make make install Of course, depending on your requirements and the relationship between PHP installation and the Internet server software, the above process may need to be modified appropriately. Use Mcrypt The advantage of Mcrypt is not only that it provides many encryption algorithms, but also that it can encrypt/decrypt data. In addition, it also provides 35 functions for processing data. Although a detailed introduction to these functions is beyond the scope of this article, I will give a brief introduction to a few typical functions. First, I will explain how to use the Mcrypt extension library to encrypt data, and then how to use it to decrypt. The following code demonstrates this process. It first encrypts the data, then displays the encrypted data on the browser, restores the encrypted data to the original string, and displays it on the browser. Use Mcrypt to encrypt and decrypt data
// Designate string to be encrypted
= "Applied Cryptography, by Bruce Schneier, is
a wonderful cryptography reference.";

// Encryption/ decryption key
key = "Four score and twenty years ago";

// Encryption Algorithm
= MCRYPT_RIJNDAEL_128;

// Create the initialization vector for added security.
= mcrypt_create_iv(mcrypt_get_iv_size(,
MCRYPT_MODE_ECB), MCRYPT_RAND);

// Output original string
print "Original string:

";

// Encrypt
= mcrypt_encrypt(, key,
, MCRYPT_MODE_CBC, );

// Convert to hexadecimal and output to browser
print "Encrypted string: ".bin2hex()."


= mcrypt_decrypt(, key,
, MCRYPT_MODE_CBC, );

print "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 c89fde4d8e7ba1e6cc9ea2485047 8c11742f5cfa1d23fe22fe8 bfbab5e Decrypted string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference. The two most typical functions in the above code are mcrypt_encrypt() and mcrypt_decrypt(), and their uses are obvious.I used the "Telegraph Codebook" mode, Mcrypt provides several encryption methods, each mode needs to be understood since each encryption method has specific characters that can affect the security of the password. For readers who have no contact with cryptosystems, the mcrypt_create_iv() function may be more interesting. Although a thorough explanation of this function is beyond the scope of this article, I will still mention the initialization vector it creates. (hence, iv), this vector can make each piece of information independent of each other. Although not all modes require this initialization variable, PHP will give a warning message if this variable is not provided in the required mode. Mhash extension library http://sourceforge.net/projects/mhash/ The Mhash extension library of version 0.8.3 supports 12 mixing algorithms. A careful inspection of the header file mhash.h of Mhash v.0.8.3 shows that it supports the following mixing algorithms: CRC32HAVAL160MD5 CRC32B HAVAL192 RIPEMD160 GOST HAVAL224 SHA1 HAVAL128 HAVAL256 TIGER Install Like Mcrypt, Mhash is not included in the PHP package. For non-Windows users, here is the installation process: Download the 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, additional configuration of Mhash may be required depending on how PHP is installed on the Internet server software. For Windows users, there is a good PHP package including the Mhash extension library at http://www.php4win.de. Just download and unzip it, and then install it according to the instructions in the readme.first document. UseMhash Mixing information is very simple, take a look at the following example: = MHASH_TIGER;
= "These are the directions to the secret fort. Two steps left, three steps right, and cha chacha.";
= mhash(, );
print "The hashed message is ". bin2hex();
?> Executing this script will result in the following output: The hashed message is 07a92a4db3a4177f19ec9034ae5400eb60d1a9fbb4ade461 The purpose of using the bin2hex() function here is to facilitate our understanding of the output. This is because the mixed result is in binary format. In order to convert it into an easy-to-understand format, it must be converted into hexadecimal format. It is important to note that shuffling is a one-way function and its results do not depend on the input, so this information can be displayed publicly. This strategy is typically used to allow users to compare downloaded files with files provided by the system administrator to ensure file integrity. Mhash has some other useful functions. For example, I need to output the name of an algorithm supported by Mhash. Since the names of all algorithms supported by Mhash start with MHASH_, this task can be accomplished by executing the following code: = MHASH_TIGER;
print "This data has been hashed with the".mhash_get_hash_name()."hashing algorithm.";
?> The resulting output is: This data has been hashed with the TIGER hashing algorithm. One last thing to note about PHP and encryption One final important thing to note about PHP and encryption is that the data transferred between the server and client is not secure in transit! PHP is a server-side technology and 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 secure server arrangements. in conclusion This article introduces one of PHP's most useful features - data encryption. It not only discusses PHP's built-in crypt() and md5() encryption functions, but also discusses powerful extension libraries for data encryption - Mcrypt and Mhash. At the end of this article, I need to point out that a truly secure PHP application should also include a secure server. Since PHP is a server-side technology, it cannot Ensure data security. Editor in charge: Xiao Li

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314395.htmlTechArticleData encryption has become more and more important in our lives, especially considering what happens on the Internet Large volumes of transactions and large amounts of data transferred. If you are interested in adopting security measures...
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),