Home Backend Development PHP Tutorial An in-depth analysis of PHP data encryption methods

An in-depth analysis of PHP data encryption methods

Jul 25, 2016 am 08:58 AM

  1. mysql>CREATE TABLE members (
  2. ->username CHAR(14) NOT NULL,
  3. ->password CHAR(32) NOT NULL,
  4. ->PRIMARY KEY(username)
  5. ->);
Copy code

Then, we assume that the following data is already stored in the table:

  1. $enteredPassword.
  2. $salt = substr($enteredPassword, 0, 2);
  3. $userPswd = crypt($enteredPassword, $salt);
  4. // $userPswd is then stored in MySQL together with the username In
Copy Code

I will be using Apache's password-response authentication configuration to prompt the user for their username and password. A little known fact about PHP is that it can pass the Apache password-response system input to the user. The name and password are identified as $PHP_AUTH_USER and $PHP_AUTH_PW, which I will use in the authentication script. Take some time to read the script below carefully and pay more attention to the explanations to better understand the following code: Application of crypt() and Apache's password-response verification system

  1. $host = "localhost";
  2. $user = "zorro";
  3. $pswd = "hell odolly";
  4. $db = "users";
  5. // Set authorization to False
  6. $authorization = 0 ;
  7. // Verify that user has entered username and password
  8. if (isset($PHP_AUTH_USER) &&isset($PHP_AUTH_PW)) :
  9. mysql_pconnect($host, $user, $pswd) or die("Can't connect to MySQL
  10. server!");
  11. mysql_select_db($db) or die("Can't select database!");
  12. // Perform the encryption
  13. $salt = substr($PHP_AUTH_PW, 0, 2);
  14. $encrypted_pswd = crypt( $PHP_AUTH_PW, $salt);
  15. // Build the query
  16. $query = "SELECT username FROM members WHERE
  17. username = '$PHP_AUTH_USER' AND
  18. password = '$encrypted_pswd'";
  19. // Execute the query
  20. if (mysql_numrows (mysql_query($query)) == 1) :
  21. $authorization = 1;
  22. endif;
  23. endif;
  24. // confirm authorization
  25. if (! $authorization) :
  26. header('WWW-Authenticate: Basic realm="Private "');
  27. header('HTTP/1.0 401 Unauthorized');
  28. print "You are unauthorized to enter this area.";
  29. exit;
  30. else :
  31. print "This is the secret data!";
  32. endif;
  33. >
Copy code

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 hash 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

  1. $msg = "This is some message that I just wrote";
  2. $enc_msg = md5($msg);
  3. print "hash: $enc_msg ";
  4. >
Copy code

Results: hash: 81ea092649ca32b5ba375e81d8f4972c Note that the result is 32 characters long. Take a look at the following table again, where the value of $msg has changed slightly: Use md5() to shuffle a slightly changed string

  1. //Note that there is one s missing in the message
  2. $msg = "This is some message that I just wrote";
  3. $enc_msg = md5($msg);
  4. print "hash2: $enc_msg
  5. " ;
  6. >
Copy code

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. Tool of. 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, 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 1 2 Next Page Last Page



Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles