Home  >  Article  >  Backend Development  >  Encryption function in PHP_PHP tutorial

Encryption function in PHP_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 16:09:55659browse


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 popularly 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. Data encryption/decryption 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 completes 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 use its crypt() function to complete one-way encryption. 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, which can affect the encrypted password, further eliminating 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 $1$ CRYPT_BLOWFISH 16-character beginning with $2$ 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: $enteredPassword.
$salt = substr($enteredPassword, 0, 2);
$userPswd = crypt($enteredPassword, $salt);
// $userPswd is then stored in MySQL together with the username middle I will be using Apache's password-response authentication configuration to prompt the user for a username and password. A little-known fact about PHP is that it recognizes usernames and passwords entered by the Apache password-response system as $PHP_AUTH_USER and $PHP_AUTH_PW. I will use these two variables in the authentication 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
$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
server!");

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 members WHERE
username = '$PHP_AUTH_USER' AND
password = ' $encrypted_pswd'";

// Execute the query

if (mysql_numrows(mysql_query($query)) == 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.";
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 hashing function can transform 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 $msg = "This is some message that I just wrote";
$enc_msg = md5($msg);
print "hash: $enc_msg ";
?> Result: hash: 81ea092649ca32b5ba375e81d8f4972c Note that the length of the result is 32 characters. Take a look at the following table again, where the value of $msg has changed slightly: Use md5() to shuffle a slightly changed string //Note that there is one s missing in the message
$msg = "This is some message that I just wrote";
$enc_msg = md5($msg);
print "hash2: $enc_msg

";
?> Results: 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 own 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, 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 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 expand 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 introduce 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.使用Mcrypt对数据进行加、解密
// 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";

?> 执行上面的脚本将会产生下面的输出: 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.     上面的代码中二个最典型的函数是mcrypt_encrypt()和mcrypt_decrypt(),它们的用途是显而易见的。我使用了“电报密码本”模式,Mcrypt提供了几种加密方式,由于每种加密方式都有可以影响密码安全的特定字符,因此每种模式都需要了解。对于没有接触过密码系统的读者来说,可能对mcrypt_create_iv()函数更有兴趣,尽管对这一函数进行彻底的解释已经超出了本篇文章的范围,但我仍然会提到它创建的初始化向量(hence, iv),这一向量可以使每条信息彼此独立。尽管不是所有的模式都需要这一初始化变量,但如果在要求的模式中没有提供这一变量,PHP就会给出警告信息。 Mhash扩展库 http://sourceforge.net/projects/mhash/     0.8.3版的Mhash扩展库支持12种混编算法,仔细检查Mhash v.0.8.3的头文件mhash.h可以知道,它支持下面的混编算法: CRC32 HAVAL160 MD5 CRC32B HAVAL192 RIPEMD160 GOST HAVAL224 SHA1 HAVAL128 HAVAL256 TIGER 安装     象Mcrypt一样,Mhash也没有包括在PHP软件包中,对于非Windows用户而言,下面是安装过程: 下载Mhash扩展库 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     象Mcrypt一样,根据PHP在互联网服务器软件上的安装方式,可能需要对Mhash进行其他的配置。     对于Windows用户而言,http://www.php4win.de中有一个很好的包括Mhash扩展库在内的PHP软件包。只要下载并进行解压缩,然后根据其中的readme.first文档中的指令进行安装即可。 使用Mhash     对信息进行混编非常简单,看一下下面的例子: $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);
?>     执行这一段脚本程序将得到下面的输出结果:The hashed message is 07a92a4db3a4177f19ec9034ae5400eb60d1a9fbb4ade461      在这里使用bin2hex()函数的目的是方便我们理解$hashed_message的输出,这是因为混编的结果是二进制格式,为了能够将它转化为易于理解的格式,必须将它转换为十六进制格式。     需要注意的是,混编是单向功能,其结果不依赖输入,因此可以公开显示这一信息。这一策略通常用于让用户比较下载文件和系统管理员提供的文件,以确保文件的完整性。      Mhash还有其他一些有用的函数。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: $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 has been hashed with the TIGER hashing algorithm. One last thing to note about PHP and encryption The last important thing to note about PHP and encryption is that the data transferred between the server and the client is not secure during transmission! 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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/314399.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