PHP的學(xué)習(xí)--PHP加密,PHP學(xué)習(xí)--PHP加密
Jun 13, 2016 am 09:22 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 報(bào)文摘要將以16字節(jié)長(zhǎng)度的原始二進(jìn)制格式返回。
這是一種不可逆加密,執(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() 返回一個(gè)基于標(biāo)準(zhǔn) UNIX DES 算法或系統(tǒng)上其他可用的替代算法的散列字符串。
參數(shù)
str -- 待散列的字符串。
salt -- 可選的鹽值字符串。如果沒(méi)有提供,算法行為將由不同的算法實(shí)現(xiàn)決定,并可能導(dǎo)致不可預(yù)料的結(jié)束。
這是也一種不可逆加密,執(zhí)行如下的代碼
<span>$password</span> = '123456'<span>; </span><span>$salt</span> = "test";<span>//</span><span> 只取前兩個(gè)</span> <span>echo</span> <span>crypt</span>(<span>$password</span>, <span>$salt</span>);
得到的結(jié)果是teMGKvBPcptKo
使用自動(dòng)鹽值的例子如下:
<span>$password</span> = <span>crypt</span>('mypassword'); <span>//</span><span> 自動(dòng)生成鹽值</span> <span>/*</span><span> 你應(yīng)當(dāng)使用 crypt() 得到的完整結(jié)果作為鹽值進(jìn)行密碼校驗(yàn),以此來(lái)避免使用不同散列算法導(dǎo)致的問(wèn)題。(如上所述,基于標(biāo)準(zhǔn) DES 算法的密碼散列使用 2 字符鹽值,但是基于 MD5 算法的散列使用 12 個(gè)字符鹽值。)</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" 字符中的兩個(gè)字符作為鹽值。在鹽值中使用非法的字符將導(dǎo)致 crypt() 失敗。
- CRYPT_EXT_DES - 擴(kuò)展的基于 DES 算法的散列。其鹽值為 9 個(gè)字符的字符串,由 1 個(gè)下劃線后面跟著 4 字節(jié)循環(huán)次數(shù)和 4 字節(jié)鹽值組成。它們被編碼成可打印字符,每個(gè)字符 6 位,有效位最少的優(yōu)先。0 到 63 被編碼為 "./0-9A-Za-z"。在鹽值中使用非法的字符將導(dǎo)致 crypt() 失敗。
- CRYPT_MD5 - MD5 散列使用一個(gè)以 $1$ 開(kāi)始的 12 字符的字符串鹽值。
- CRYPT_BLOWFISH - Blowfish 算法使用如下鹽值:“$2a$”,一個(gè)兩位 cost 參數(shù),“$” 以及 64 位由 “./0-9A-Za-z” 中的字符組合而成的字符串。在鹽值中使用此范圍之外的字符將導(dǎo)致 crypt() 返回一個(gè)空字符串。兩位 cost 參數(shù)是循環(huán)次數(shù)以 2 為底的對(duì)數(shù),它的范圍是 04-31,超出這個(gè)范圍將導(dǎo)致 crypt() 失敗。
- CRYPT_SHA256 - SHA-256 算法使用一個(gè)以 $5$ 開(kāi)頭的 16 字符字符串鹽值進(jìn)行散列。如果鹽值字符串以 “rounds=
$” 開(kāi)頭,N 的數(shù)字值將被用來(lái)指定散列循環(huán)的執(zhí)行次數(shù),這點(diǎn)很像 Blowfish 算法的 cost 參數(shù)。默認(rèn)的循環(huán)次數(shù)是 5000,最小是 1000,最大是 999,999,999。超出這個(gè)范圍的 N 將會(huì)被轉(zhuǎn)換為最接近的值。 - CRYPT_SHA512 - SHA-512 算法使用一個(gè)以 $6$ 開(kāi)頭的 16 字符字符串鹽值進(jìn)行散列。如果鹽值字符串以 “rounds=
$” 開(kāi)頭,N 的數(shù)字值將被用來(lái)指定散列循環(huán)的執(zhí)行次數(shù),這點(diǎn)很像 Blowfish 算法的 cost 參數(shù)。默認(rèn)的循環(huán)次數(shù)是 5000,最小是 1000,最大是 999,999,999。超出這個(gè)范圍的 N 將會(huì)被轉(zhuǎn)換為最接近的值。
3. Sha1加密
string sha1 ( string $str [, bool $raw_output = false ] )
參數(shù)
str -- 輸入字符串。
raw_output -- 如果可選的 raw_output 參數(shù)被設(shè)置為 TRUE,那么 sha1 摘要將以 20 字符長(zhǎng)度的原始格式返回,否則返回值是一個(gè) 40 字符長(zhǎng)度的十六進(jìn)制數(shù)字。
這是也一種不可逆加密,執(zhí)行如下代碼:
<span>$password</span> = '123456'<span>; </span><span>echo</span> <span>sha1</span>(<span>$password</span>);
得到的結(jié)果是7c4a8d09ca3762af61e59520943dc26494f8941b
以上幾種雖然是不可逆加密,但是也可以根據(jù)查字典的方式去解密。如下的地址中就提供了可以將上面的加密結(jié)果解密出來(lái)的功能。
http://www.cmd5.com/
那大家是不是加了就算加了密,也沒(méi)用啊,其實(shí)不然,只要你的加密足夠復(fù)雜,被破解出的可能性就越小,比如用以上三種加密方式混合加密,之后我會(huì)推薦給大家一個(gè)php的加密庫(kù)。
4. URL加密
string urlencode ( string $str )
此函數(shù)便于將字符串編碼并將其用于 URL 的請(qǐng)求部分,同時(shí)它還便于將變量傳遞給下一頁(yè)。
返回字符串,此字符串中除了 -_. 之外的所有非字母數(shù)字字符都將被替換成百分號(hào)(%)后跟兩位十六進(jìn)制數(shù),空格則編碼為加號(hào)(+)。此編碼與 WWW 表單 POST 數(shù)據(jù)的編碼方式是一樣的,同時(shí)與 application/x-www-form-urlencoded 的媒體類型編碼方式一樣。由于歷史原因,此編碼在將空格編碼為加號(hào)(+)方面與 RFC1738 編碼不同。
string urldecode ( string $str )
解碼給出的已編碼字符串中的任何 %##。 加號(hào)('+')被解碼成一個(gè)空格字符。
這是一種可逆加密,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)頁(yè)上展示的,就將\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 對(duì) data 進(jìn)行編碼。
設(shè)計(jì)此種編碼是為了使二進(jìn)制數(shù)據(jù)可以通過(guò)非純 8-bit 的傳輸層傳輸,例如電子郵件的主體。
Base64-encoded 數(shù)據(jù)要比原始數(shù)據(jù)多占用 33% 左右的空間。
string base64_decode ( string $data [, bool $strict = false ] )
對(duì) base64 編碼的 data 進(jìn)行解碼。
參數(shù)
data -- 編碼過(guò)的數(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 測(cè)試,在存入數(shù)據(jù)庫(kù)之前進(jìn)行哈希保護(hù)用戶密碼的標(biāo)準(zhǔn)方式。 許多常用的哈希算法如 md5,甚至是 sha1 對(duì)于密碼存儲(chǔ)都是不安全的, 因?yàn)轳斂湍軌蚴褂媚切┧惴ㄝp而易舉地破解密碼。
對(duì)密碼進(jìn)行哈希最安全的方法是使用 bcrypt 算法。開(kāi)源的 phpass 庫(kù)以一個(gè)易于使用的類來(lái)提供該功能。
<?<span>php </span><span>//</span><span> Include phpass 庫(kù)</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> 計(jì)算密碼的哈希值。$hashedPassword 是一個(gè)長(zhǎng)度為 60 個(gè)字符的字符串.</span> <span>$hashedPassword</span> = <span>$hasher</span>->HashPassword('my super cool password'<span>); </span><span>//</span><span> 你現(xiàn)在可以安全地將 $hashedPassword 保存到數(shù)據(jù)庫(kù)中! // 通過(guò)比較用戶輸入內(nèi)容(產(chǎn)生的哈希值)和我們之前計(jì)算出的哈希值,來(lái)判斷用戶是否輸入了正確的密碼</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> ?>
陷阱
- 許多資源可能推薦你在哈希之前對(duì)你的密碼“加鹽”。想法很好,但 phpass 在 HashPassword() 函數(shù)中已經(jīng)對(duì)你的密碼“加鹽”了,這意味著你不需要自己“加鹽”。
進(jìn)一步閱讀
- phpass
- 為什么使用 md5 或 sha 哈希密碼是不安全的(中文)
- 怎樣安全地存儲(chǔ)密碼
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;
} 可以在上面這段代碼獲得加密的密碼 其實(shí)也就是用戶名和密碼同過(guò)md5()方法加密!
?
給你個(gè)我常用的,也符合你的要求,很好用哦。 /**
* 采用RC4為核心算法,通過(guò)加密或者解密用戶信息
* @param $string - 加密或解密的串
* @param $operation - DECODE 解密;ENCODE 加密
* @param $key - 密鑰 默認(rèn)為AUTHKEY常量
* @return 返回字符串
*/ define('AUTHKEY', 'yl_chen');
function MooAuthCode($string, $operation = 'DECODE', $key = '', $expiry = 0) { /**
* $ckey_length 隨機(jī)密鑰長(zhǎng)度 取值 0-32;
* 加入隨機(jī)密鑰,可以令密文無(wú)任何規(guī)律,即便是原文和密鑰完全相同,加密結(jié)果也會(huì)每次不同,增大破解難度。
* 取值越大,密文變動(dòng)規(guī)律越大,密文變化 = 16 的 $ckey_length 次方
* 當(dāng)此值為 0 時(shí),則不產(chǎn)生隨機(jī)密鑰
*/
$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 $rndkey[$i] = ord($cryptkey[$i % $key_length]);
} for($j = $i = 0; $i $j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
} for($a = $j = $i = 0; $i $a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256......余下全文>>
?

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)

Hot Topics

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach
