search
HomeBackend DevelopmentPHP TutorialIntroduction to several ways to implement encryption in PHP, several ways to implement encryption in PHP_PHP tutorial

Introduction to several ways to implement encryption in PHP, several ways to implement encryption in PHP

The encryption methods in PHP are as follows

1. MD5 encryption

string md5 ( string $str [, bool $raw_output = false ] )

Parameters

str -- Original string.

raw_output -- If the optional raw_output is set to TRUE, the MD5 message digest will be returned in raw binary format with a length of 16 bytes.

This is an irreversible encryption, execute the following code

$password = '123456';
echo md5($password);
The result is e10adc3949ba59abbe56e057f20f883e

2. Crype encryption
string crypt ( string $str [, string $salt ] )

crypt() Returns a hashed string based on the standard UNIX DES algorithm or another alternative algorithm available on the system.

Parameters

str -- The string to be hashed.

salt -- Optional salt value string. If not provided, algorithm behavior will be determined by different algorithm implementations and may lead to unpredictable endings.

This is also an irreversible encryption, execute the following code

Copy code The code is as follows:

$password = '123456';
$salt = "test"; // Only take the first two
echo crypt($password, $salt);

The result is teMGKvBPcptKo

An example of using automatic salt value is as follows:

Copy code The code is as follows:

$password = crypt('mypassword'); // Automatically generate salt value
/* You should use the complete result of crypt() as a salt value for password verification to avoid problems caused by using different hashing algorithms. (As mentioned above, password hashes based on the standard DES algorithm use a 2-character salt, but hashes based on the MD5 algorithm use a 12-character salt.) */
if (crypt('mypassword', $password) == $password) {
echo "Password verified!";
}

The execution result is the output Password verified!

Examples of using crypt() with different hash types are as follows:

Copy code The code is 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.4T8M
Extended DES: _J9..rasmBYk8r9AiWNc
MD5:                                                                                                           Blowfish: $2a$07$usesomesillystringfore2uDLvp1Ii2e./U9C8sBjqp8I90dH6hi
SHA-256: $5$rounds=5000$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.6
SHA-512: $6$rounds=5000$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
On systems where the crypt() function supports multi-hashing, the following constants are set to 0 or 1 depending on whether the corresponding type is available:

CRYPT_STD_DES - A hash based on the standard DES algorithm using two of the "./0-9A-Za-z" characters as the salt. Using illegal characters in the salt will cause crypt() to fail.

CRYPT_EXT_DES - Extended hashing based on the DES algorithm. The salt is a 9-character string consisting of an underscore followed by the 4-byte cycle count and the 4-byte salt. They are encoded into printable characters, 6 bits each, with the least significant bits first. 0 to 63 are encoded as "./0-9A-Za-z". Using illegal characters in the salt will cause crypt() to fail.
CRYPT_MD5 - MD5 hashing uses a 12-character string salt starting with $1$.
CRYPT_BLOWFISH - The Blowfish algorithm uses the following salt: "$2a$", a two-digit cost parameter, "$", and a 64-bit string consisting of characters from "./0-9A-Za-z". Using characters outside this range in the salt will cause crypt() to return an empty string. The two-digit cost parameter is the base-2 logarithm of the number of cycles. Its range is 04-31. Exceeding this range will cause crypt() to fail.
CRYPT_SHA256 - The SHA-256 algorithm hashes using a 16-character string salt starting with $5$. If the salt string begins with "rounds=$", the numeric value of N will be used to specify the number of hashing rounds to execute, much like the cost parameter of the Blowfish algorithm. The default number of loops is 5000, the minimum is 1000, and the maximum is 999,999,999. N outside this range will be converted to the nearest value.
CRYPT_SHA512 - The SHA-512 algorithm hashes using a 16-character string salt starting with $6$. If the salt string begins with "rounds=$", the numeric value of N will be used to specify the number of hashing rounds to execute, much like the cost parameter of the Blowfish algorithm. The default number of loops is 5000, the minimum is 1000, and the maximum is 999,999,999. N outside 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 will be returned in raw format with a length of 20 characters, otherwise the return value is a 40-character hexadecimal number.

This is also an irreversible encryption, execute the following code:

$password = '123456';

echo sha1($password);
The result obtained is 7c4a8d09ca3762af61e59520943dc26494f8941b

Although the above types are irreversible encryption, they can also be decrypted by looking up the dictionary. The following address provides the function to decrypt the above encryption result.

http://www.cmd5.com/

Do you think it is useless even if you add encryption? In fact, it is not the case. As long as your encryption is complex enough, the possibility of being cracked is smaller. For example, you can use a mixture of the above three encryption methods to encrypt. I will recommend to everyone a php encryption library.

4. URL encryption

string urlencode ( string $str )

This function facilitates encoding a string and using it in the request part of the URL, and it also facilitates passing variables to the next page.

Returns a string in which all non-alphanumeric characters except -_. will be replaced with a percent sign (%) followed by two hexadecimal digits, and spaces are encoded as plus signs ( +). This encoding is the same as the encoding of WWW form POST data, and the same encoding as the application/x-www-form-urlencoded media type. For historical reasons, this encoding differs from the RFC1738 encoding in encoding spaces as plus signs (+).

string urldecode ( string $str )

Decode any %## in the given encoded string. The plus sign ('+') is decoded into a space character.

This is a reversible encryption. The urlencode method is used for encryption and the urldecode method is used for decryption. Execute the following code:

$url = 'http://www.xxx.com/CraryPrimitiveMan/';

$encodeUrl = urlencode($url);
echo $encodeUrl . "n";// If it is displayed on a web page, change n to

echo urldecode($encodeUrl);
The results obtained are as follows

http%3A%2F%2Fwww.xxx.com%2FCraryPrimitiveMan%2F

http://www.xxx.com/CraryPrimitiveMan/
The method of encrypting URLs based on RFC 3986 is as follows:

Copy code The code is as follows:

function myUrlEncode($string) {
$entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D') ;
$replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", " $", ",", "/", "?", "%", "#", "[", "]");
Return str_replace($entities, $replacements, urlencode($string));
}

5. Base64 information encoding and encryption

string base64_encode ( string $data )

Encode data using base64.

This encoding is designed to enable binary data to be transmitted over non-pure 8-bit transport layers, such as the body of an email.

Base64-encoded data takes up about 33% more space than the original data.

string base64_decode ( string $data [, bool $strict = false ] )

Decode base64 encoded data.

Parameters

data -- encoded data.

strict -- Returns FALSE if the input data exceeds the base64 alphabet.

Execute the following code:

Copy code The code is as follows:

$name = 'CraryPrimitiveMan';
$encodeName = base64_encode($name);
echo $encodeName . "n";
echo base64_decode($encodeName);

The results are as follows

Copy code The code is as follows:

Q3JhcnlQcmltaXRpdmVNYW4=
CraryPrimitiveMan

Recommend phpass

Tested with phpass 0.3, the standard way to protect user passwords by hashing them before storing them in the database. Many commonly used hashing algorithms such as md5 and even sha1 are not secure for password storage because hackers can easily crack passwords using those algorithms.

The most secure way to hash passwords is to use the bcrypt algorithm. The open source phpass library provides this functionality in an easy-to-use class.

Copy code The code is as follows:

// Include phpass library
require_once('phpass-03/PasswordHash.php')
// Initialize the hasher to be non-portable (this is safer)
$hasher = new PasswordHash(8, false);
// Calculate the hash value of the password. $hashedPassword is a 60-character string.
$hashedPassword = $hasher->HashPassword('my super cool password');
// You can now safely save $hashedPassword to the database!
// Determine whether the user entered the correct password by comparing the user input content (generated hash value) with the hash value we calculated previously
$hasher->CheckPassword('the wrong password', $hashedPassword); // false
$hasher->CheckPassword('my super cool password', $hashedPassword); // true
?>

The above is the introduction of this article about PHP encryption method. I hope you will like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/959105.htmlTechArticleIntroduction to several ways to implement encryption in PHP. Several ways to implement encryption in PHP. The encryption methods in PHP are as follows 1 . MD5 encrypted string md5 ( string $str [, bool $raw_output = false ] ) Parameter str -...
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
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

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

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

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),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software