search
HomeBackend DevelopmentPHP Tutorialphp returns a string encrypted using DES and Blowfish and MD5 algorithms function crypt()

Definition and Usage

The crypt() function returns a string encrypted using the DES, Blowfish or MD5 algorithm.

This function behaves differently on different operating systems, and some operating systems support more than one algorithm type. At installation time, PHP checks what algorithms are available and what algorithms are used.

The exact algorithm depends on the format and length of the salt parameter. Salt can make encryption more secure by increasing the number of strings generated from a specific string with a specific encryption method.

Here are some constants used with the crypt() function. These constant values ​​are set by PHP during installation.

Constant:

  • [CRYPT_SALT_LENGTH] - Default encryption length. Use standard DES encryption with a length of 2

  • ##[CRYPT_STD_DES] - Standard DES based encryption with a 2 character salt from the alphabet "./0-9A-Za-z ". Using invalid characters in salt will cause the function to fail.

  • [CRYPT_EXT_DES] - Extended DES-based encryption with a 9-character salt consisting of an underscore, followed by a 4-byte iteration number and a 4-byte salt. . These are encoded as printable characters, 6 bits each, least significant character first. Values ​​0 to 63 are encoded as "./0-9A-Za-z". Using invalid characters in salt will cause the function to fail.

  • [CRYPT_MD5] - MD5 encryption with a 12-character salt, starting with $1$.

  • [CRYPT_BLOWFISH] - Blowfish encryption has a salt starting with $2a$, $2x$ or $2y$, a two-digit cost parameter "$", and from letters 22 characters in the table "./0-9A-Za-z". Using characters outside the alphabet will cause the function to return a string of length 0. The "$" parameter is the base 2 logarithm of the number of iterations of the Blowfish hashing algorithm and must be in the range 04-31. Values ​​outside this range will cause the function to fail.

  • [CRYPT_SHA_256] - SHA-256 encryption with a 16-character salt, starting with $5$. If the salt string starts with "rounds=$", the numeric value of N is used to represent the number of times the hashing round is executed, similar to the cost parameter in Blowfish. The default number of loops is 5000, the minimum value is 1000, and the maximum value is 999,999,999. Any value of N outside this range will be converted to the nearest boundary value.

  • [CRYPT_SHA_512] - SHA-512 encryption with a 16-character salt, starting with $6$. If the salt string starts with "rounds=$", the numeric value of N is used to represent the number of times the hashing round is executed, similar to the cost parameter in Blowfish. The default number of loops is 5000, the minimum value is 1000, and the maximum value is 999,999,999. Any value of N outside this range will be converted to the nearest boundary value.

On systems where this function supports multiple algorithms, the above constant is set to "1" if supported, and "0" otherwise.

Note: There is no corresponding decryption function. The crypt() function uses a one-way algorithm.

Syntax

crypt(str,salt)

Parameters Description

str Required. Specifies the string to be encoded. ​

salt ​ Optional. A string used to increase the number of characters being encoded to make the encoding more secure. If no salt argument is provided, one will be randomly generated each time the function is called. ​

Technical details

Return value: ​ ​ ​ Returns the encrypted string, or if it fails, returns a string less than 13 characters and guaranteed to be different from the salt.

PHP version: 4+

更新日志:         在 PHP 5.3.7 中,新增了 $2x$ 和 $2y$ Blowfish 模式,用来处理潜在的高位攻击。                          

                          在 PHP 5.3.2 中,新增了常量 SHA-256 和 SHA-512。

                          自 PHP 5.3.2 起,Blowfish 在无效的循环将返回 "failure" 字符串("*0" 或 "*1"),而不是后退到 DES。
                          自 PHP 5.3.0 起,PHP 自带 MD5 加密实现、标准 DES 实现、扩展 DES 实现以及 Blowfish 算法。如果系统不支持上述的算法,将使用 PHP 自带的算法实现。    

实例

实例 1

在本实例中,我们将测试不同的算法:

<?php
// 2 character salt
if (CRYPT_STD_DES == 1)
{
echo "Standard DES: ".crypt(&#39;something&#39;,&#39;st&#39;)."n<br>"; 
}
else
{
echo "Standard DES not supported.n<br>";
}

// 4 character salt
if (CRYPT_EXT_DES == 1)
{
echo "Extended DES: ".crypt(&#39;something&#39;,&#39;_S4..some&#39;)."n<br>";
}
else
{
echo "Extended DES not supported.n<br>";
}

// 12 character salt starting with $1$ 
if (CRYPT_MD5 == 1)
{
echo "MD5: ".crypt(&#39;something&#39;,&#39;$1$somethin$&#39;)."n<br>"; 
}
else
{
echo "MD5 not supported.n<br>";
}

// Salt starting with $2a$. The two digit cost parameter: 09. 22 characters 
if (CRYPT_BLOWFISH == 1)
{
echo "Blowfish: ".crypt(&#39;something&#39;,&#39;$2a$09$anexamplestringforsalt$&#39;)."n<br>"; 
}
else
{
echo "Blowfish DES not supported.n<br>";
}

// 16 character salt starting with $5$. The default number of rounds is 5000.
if (CRYPT_SHA256 == 1) 
{
echo "SHA-256: ".crypt(&#39;something&#39;,&#39;$5$rounds=5000$anexamplestringforsalt$&#39;)."n<br>"; }
else
{
echo "SHA-256 not supported.n<br>";
}

// 16 character salt starting with $5$. The default number of rounds is 5000.
if (CRYPT_SHA512 == 1) 
{
echo "SHA-512: ".crypt(&#39;something&#39;,&#39;$6$rounds=5000$anexamplestringforsalt$&#39;); 
}
else
{
echo "SHA-512 not supported.";
}
?>

上面的代码输出如下(取决于操作系统):

Standard DES: stqAdD7zlbByI
Extended DES: _S4..someQXidlBpTUu6
MD5: $1$somethin$4NZKrUlY6r7K7.rdEOZ0w.
Blowfish: $2a$09$anexamplestringforsaleLouKejcjRlExmf1671qw3Khl49R3dfu
SHA-256: $5$rounds=5000$anexamplestringf$KIrctqsxo2wrPg5Ag/hs4jTi4PmoNKQUGWFXlVy9vu9
SHA-512: $6$rounds=5000$anexamplestringf$Oo0skOAdUFXkQxJpwzO05wgRHG0dhuaPBaOU/
oNbGpCEKlf/7oVM5wn6AN0w2vwUgA0O24oLzGQpp1XKI6LLQ0.

一、代码

<?php 
 $str = &#39;应用crypt()函数进行单向加密!&#39;;     //声明字符串变量$str 
 echo &#39;加密前$str的值为:&#39;.$str; 
 $crypttostr = crypt($str);      //对变量$str加密 
 echo &#39;<p>加密后$str的值为:&#39;.$crypttostr;  //输出加密后的变量 
?>

二、运行结果

参数不带salt,每次加密得出的密文都不一样。
加密前$str的值为:应用crypt()函数进行单向加密!
加密后$str的值为:$1$Re4.Gg4.$D.yd00xX0fFfIfp6KrKGN0

The above is the detailed content of php returns a string encrypted using DES and Blowfish and MD5 algorithms function crypt(). For more information, please follow other related articles on the PHP Chinese website!

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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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 Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools