


PHP learning--PHP encryption, PHP learning--PHP encryption_PHP tutorial
Jul 13, 2016 am 10:15 AMPHP的學(xué)習(xí)--PHP加密,PHP學(xué)習(xí)--PHP加密
PHP中的加密方式有如下幾種
1. MD5加密
string md5 ( string $str [, bool $raw_output = false ] )?
參數(shù)
str ?-- ?原始字符串。
raw_output??-- ?如果可選的 raw_output 被設(shè)置為 TRUE,那么 MD5 報文摘要將以16字節(jié)長度的原始二進制格式返回。
這是一種不可逆加密,執(zhí)行如下的代碼
<span>$password</span> = '123456'<span>; </span><span>echo</span> <span>md5</span>(<span>$password</span>);
得到結(jié)果是e10adc3949ba59abbe56e057f20f883e
2. Crype加密
string crypt ( string $str [, string $salt ] )
crypt() 返回一個基于標(biāo)準(zhǔn) UNIX DES 算法或系統(tǒng)上其他可用的替代算法的散列字符串。
參數(shù)
str -- 待散列的字符串。
salt -- 可選的鹽值字符串。如果沒有提供,算法行為將由不同的算法實現(xiàn)決定,并可能導(dǎo)致不可預(yù)料的結(jié)束。
這是也一種不可逆加密,執(zhí)行如下的代碼
<span>$password</span> = '123456'<span>; </span><span>$salt</span> = "test";<span>//</span><span> 只取前兩個</span> <span>echo</span> <span>crypt</span>(<span>$password</span>, <span>$salt</span>);
得到的結(jié)果是teMGKvBPcptKo
使用自動鹽值的例子如下:
<span>$password</span> = <span>crypt</span>('mypassword'); <span>//</span><span> 自動生成鹽值</span> <span>/*</span><span> 你應(yīng)當(dāng)使用 crypt() 得到的完整結(jié)果作為鹽值進行密碼校驗,以此來避免使用不同散列算法導(dǎo)致的問題。(如上所述,基于標(biāo)準(zhǔn) DES 算法的密碼散列使用 2 字符鹽值,但是基于 MD5 算法的散列使用 12 個字符鹽值。)</span><span>*/</span> <span>if</span> (<span>crypt</span>('mypassword', <span>$password</span>) == <span>$password</span><span>) { </span><span>echo</span> "Password verified!"<span>; }</span>
執(zhí)行結(jié)果是輸出 Password verified!
以不同散列類型使用 crypt()的例子如下:
<span>if</span> (CRYPT_STD_DES == 1<span>) { </span><span>echo</span> 'Standard DES: ' . <span>crypt</span>('rasmuslerdorf', 'rl') . "\n"<span>; } </span><span>if</span> (CRYPT_EXT_DES == 1<span>) { </span><span>echo</span> 'Extended DES: ' . <span>crypt</span>('rasmuslerdorf', '_J9..rasm') . "\n"<span>; } </span><span>if</span> (CRYPT_MD5 == 1<span>) { </span><span>echo</span> 'MD5: ' . <span>crypt</span>('rasmuslerdorf', '$1$rasmusle$') . "\n"<span>; } </span><span>if</span> (CRYPT_BLOWFISH == 1<span>) { </span><span>echo</span> 'Blowfish: ' . <span>crypt</span>('rasmuslerdorf', '$2a$07$usesomesillystringforsalt$') . "\n"<span>; } </span><span>if</span> (CRYPT_SHA256 == 1<span>) { </span><span>echo</span> 'SHA-256: ' . <span>crypt</span>('rasmuslerdorf', '$5$rounds=5000$usesomesillystringforsalt$') . "\n"<span>; } </span><span>if</span> (CRYPT_SHA512 == 1<span>) { </span><span>echo</span> 'SHA-512: ' . <span>crypt</span>('rasmuslerdorf', '$6$rounds=5000$usesomesillystringforsalt$') . "\n"<span>; }</span>
其結(jié)果如下
<span>Standard DES: rl.3StKT.4T8M Extended DES: _J9..rasmBYk8r9AiWNc MD5: $</span><span>1</span><span>$rasmusle$rISCgZzpwk3UhDidwXvin0 Blowfish: $2a$</span><span>07</span>$usesomesillystringfore2uDLvp1Ii2e./<span>U9C8sBjqp8I90dH6hi SHA</span>-<span>256</span>: $<span>5</span>$rounds=<span>5000</span>$usesomesillystri$KqJWpanXZHKq2BOB43TSaYhEWsQ1Lr5QNyPCDH/Tp.<span>6</span><span> SHA</span>-<span>512</span>: $<span>6</span>$rounds=<span>5000</span>$usesomesillystri$D4IrlXatmP7rx3P3InaxBeoomnAihCKRVQP22JZ6EY47Wc6BkroIuUUBOov1i.S5KPgErtP/EN5mcO.ChWQW21
在 crypt() 函數(shù)支持多重散列的系統(tǒng)上,下面的常量根據(jù)相應(yīng)的類型是否可用被設(shè)置為 0 或 1:
- CRYPT_STD_DES - 基于標(biāo)準(zhǔn) DES 算法的散列使用 "./0-9A-Za-z" 字符中的兩個字符作為鹽值。在鹽值中使用非法的字符將導(dǎo)致 crypt() 失敗。
- CRYPT_EXT_DES - 擴展的基于 DES 算法的散列。其鹽值為 9 個字符的字符串,由 1 個下劃線后面跟著 4 字節(jié)循環(huán)次數(shù)和 4 字節(jié)鹽值組成。它們被編碼成可打印字符,每個字符 6 位,有效位最少的優(yōu)先。0 到 63 被編碼為 "./0-9A-Za-z"。在鹽值中使用非法的字符將導(dǎo)致 crypt() 失敗。
- CRYPT_MD5 - MD5 散列使用一個以 $1$ 開始的 12 字符的字符串鹽值。
- CRYPT_BLOWFISH - Blowfish 算法使用如下鹽值:“$2a$”,一個兩位 cost 參數(shù),“$” 以及 64 位由 “./0-9A-Za-z” 中的字符組合而成的字符串。在鹽值中使用此范圍之外的字符將導(dǎo)致 crypt() 返回一個空字符串。兩位 cost 參數(shù)是循環(huán)次數(shù)以 2 為底的對數(shù),它的范圍是 04-31,超出這個范圍將導(dǎo)致 crypt() 失敗。
- CRYPT_SHA256 - SHA-256 算法使用一個以 $5$ 開頭的 16 字符字符串鹽值進行散列。如果鹽值字符串以 “rounds=
$” 開頭,N 的數(shù)字值將被用來指定散列循環(huán)的執(zhí)行次數(shù),這點很像 Blowfish 算法的 cost 參數(shù)。默認(rèn)的循環(huán)次數(shù)是 5000,最小是 1000,最大是 999,999,999。超出這個范圍的 N 將會被轉(zhuǎn)換為最接近的值。 - CRYPT_SHA512 - SHA-512 算法使用一個以 $6$ 開頭的 16 字符字符串鹽值進行散列。如果鹽值字符串以 “rounds=
$” 開頭,N 的數(shù)字值將被用來指定散列循環(huán)的執(zhí)行次數(shù),這點很像 Blowfish 算法的 cost 參數(shù)。默認(rèn)的循環(huán)次數(shù)是 5000,最小是 1000,最大是 999,999,999。超出這個范圍的 N 將會被轉(zhuǎn)換為最接近的值。
3. Sha1加密
string sha1 ( string $str [, bool $raw_output = false ] )
參數(shù)
str -- 輸入字符串。
raw_output -- 如果可選的 raw_output 參數(shù)被設(shè)置為 TRUE,那么 sha1 摘要將以 20 字符長度的原始格式返回,否則返回值是一個 40 字符長度的十六進制數(shù)字。
這是也一種不可逆加密,執(zhí)行如下代碼:
<span>$password</span> = '123456'<span>; </span><span>echo</span> <span>sha1</span>(<span>$password</span>);
得到的結(jié)果是7c4a8d09ca3762af61e59520943dc26494f8941b
以上幾種雖然是不可逆加密,但是也可以根據(jù)查字典的方式去解密。如下的地址中就提供了可以將上面的加密結(jié)果解密出來的功能。
http://www.cmd5.com/
那大家是不是加了就算加了密,也沒用啊,其實不然,只要你的加密足夠復(fù)雜,被破解出的可能性就越小,比如用以上三種加密方式混合加密,之后我會推薦給大家一個php的加密庫。
4. URL加密
string urlencode ( string $str )
此函數(shù)便于將字符串編碼并將其用于 URL 的請求部分,同時它還便于將變量傳遞給下一頁。
返回字符串,此字符串中除了 -_. 之外的所有非字母數(shù)字字符都將被替換成百分號(%)后跟兩位十六進制數(shù),空格則編碼為加號(+)。此編碼與 WWW 表單 POST 數(shù)據(jù)的編碼方式是一樣的,同時與 application/x-www-form-urlencoded 的媒體類型編碼方式一樣。由于歷史原因,此編碼在將空格編碼為加號(+)方面與 RFC1738 編碼不同。
string urldecode ( string $str )
解碼給出的已編碼字符串中的任何 %##。 加號('+')被解碼成一個空格字符。
這是一種可逆加密,urlencode方法用于加密,urldecode方法用于解密,執(zhí)行如下代碼:
<span>$url</span> = 'http://www.cnblogs.com/CraryPrimitiveMan/'<span>; </span><span>$encodeUrl</span> = <span>urlencode</span>(<span>$url</span><span>); </span><span>echo</span> <span>$encodeUrl</span> . "\n";<span>//</span><span> 如果是在網(wǎng)頁上展示的,就將\n修改為<br/></span> <span>echo</span> <span>urldecode</span>(<span>$encodeUrl</span>);
得到的結(jié)果如下
http%3A%2F%2Fwww.cnblogs.com%2FCraryPrimitiveMan%<span>2F http</span>:<span>//</span><span>www.cnblogs.com/CraryPrimitiveMan/</span>
基于RFC 3986的加密URL的方法如下:
<span>function</span> myUrlEncode(<span>$string</span><span>) { </span><span>$entities</span> = <span>array</span>('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'<span>); </span><span>$replacements</span> = <span>array</span>('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]"<span>); </span><span>return</span> <span>str_replace</span>(<span>$entities</span>, <span>$replacements</span>, <span>urlencode</span>(<span>$string</span><span>)); }</span>
5. Base64信息編碼加密
string base64_encode ( string $data )
使用 base64 對 data 進行編碼。
設(shè)計此種編碼是為了使二進制數(shù)據(jù)可以通過非純 8-bit 的傳輸層傳輸,例如電子郵件的主體。
Base64-encoded 數(shù)據(jù)要比原始數(shù)據(jù)多占用 33% 左右的空間。
string base64_decode ( string $data [, bool $strict = false ] )
對 base64 編碼的 data 進行解碼。
參數(shù)
data -- 編碼過的數(shù)據(jù)。
strict -- 如果輸入的數(shù)據(jù)超出了 base64 字母表,則返回 FALSE。
執(zhí)行如下代碼:
<span>$name</span> = 'CraryPrimitiveMan'<span>; </span><span>$encodeName</span> = <span>base64_encode</span>(<span>$name</span><span>); </span><span>echo</span> <span>$encodeName</span> . "\n"<span>; </span><span>echo</span> <span>base64_decode</span>(<span>$encodeName</span>);
其結(jié)果如下
Q3JhcnlQcmltaXRpdmVNYW4=<span> CraryPrimitiveMan</span>
推薦phpass
經(jīng) phpass 0.3 測試,在存入數(shù)據(jù)庫之前進行哈希保護用戶密碼的標(biāo)準(zhǔn)方式。 許多常用的哈希算法如 md5,甚至是 sha1 對于密碼存儲都是不安全的, 因為駭客能夠使用那些算法輕而易舉地破解密碼。
對密碼進行哈希最安全的方法是使用 bcrypt 算法。開源的 phpass 庫以一個易于使用的類來提供該功能。
<?<span>php </span><span>//</span><span> Include phpass 庫</span> <span>require_once</span>('phpass-03/PasswordHash.php'<span>) </span><span>//</span><span> 初始化散列器為不可移植(這樣更安全)</span> <span>$hasher</span> = <span>new</span> PasswordHash(8, <span>false</span><span>); </span><span>//</span><span> 計算密碼的哈希值。$hashedPassword 是一個長度為 60 個字符的字符串.</span> <span>$hashedPassword</span> = <span>$hasher</span>->HashPassword('my super cool password'<span>); </span><span>//</span><span> 你現(xiàn)在可以安全地將 $hashedPassword 保存到數(shù)據(jù)庫中! // 通過比較用戶輸入內(nèi)容(產(chǎn)生的哈希值)和我們之前計算出的哈希值,來判斷用戶是否輸入了正確的密碼</span> <span>$hasher</span>->CheckPassword('the wrong password', <span>$hashedPassword</span>); <span>//</span><span> false</span> <span>$hasher</span>->CheckPassword('my super cool password', <span>$hashedPassword</span>); <span>//</span><span> true</span> ?>
陷阱
- 許多資源可能推薦你在哈希之前對你的密碼“加鹽”。想法很好,但 phpass 在 HashPassword() 函數(shù)中已經(jīng)對你的密碼“加鹽”了,這意味著你不需要自己“加鹽”。
進一步閱讀
- phpass
- 為什么使用 md5 或 sha 哈希密碼是不安全的(中文)
- 怎樣安全地存儲密碼
function ChangeMsg(msgu,msgp)
{
if(msgu!="" && msgp!="")
{
delmsg = md5(msgu);
rname = substr(delmsg,5,1).",".substr(delmsg,7,1).",".substr(delmsg,15,1).",".substr(delmsg,17,1);
rnamearray = explode(',',rname);
rpass = md5(msgp);
r_msg = str_replace(rnamearray, "", rpass);
}else{
r_msg = msgp;
}
return r_msg;
} 可以在上面這段代碼獲得加密的密碼 其實也就是用戶名和密碼同過md5()方法加密!
?
I’ll give you one that I use frequently, and it meets your requirements. It’s very useful. /**
* Use RC4 as the core algorithm to encrypt or decrypt user information
* @param $string - the encrypted or decrypted string
* @param $operation - DECODE decryption; ENCODE encryption
* @param $key - the key defaults to AUTHKEY constant
* @return return string
*/ define('AUTHKEY', 'yl_chen');
function MooAuthCode($string, $operation = ' DECODE', $key = '', $expiry = 0) { /**
* $ckey_length random key length value 0-32;
* Adding a random key can make the ciphertext irregular. , even if the original text and key are exactly the same, the encryption result will be different every time, increasing the difficulty of cracking.
* The larger the value, the greater the ciphertext change pattern. Ciphertext change = 16 to the power of $ckey_length
* When this value is 0, no random key will be generated
*/
$ckey_length = 4;
$key = md5($key ? $key : md5(AUTHKEY.$_SERVER['HTTP_USER_AGENT']));
$keya = md5(substr($key, 0, 16 ));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : ''; $cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey); $string = $ operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string); $result = '';
$box = range(0, 255); $rndkey = array();
for ($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
} for($j = $ i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[ $i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
} for($a = $j = $i = 0 ; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256.... ..The rest of the full text>>

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
