国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊(cè) 通過PHP的內(nèi)置函數(shù),通過DES算法對(duì)數(shù)據(jù)加密和解密

通過PHP的內(nèi)置函數(shù),通過DES算法對(duì)數(shù)據(jù)加密和解密

Jun 13, 2016 pm 12:00 PM
des php built-in Write function encryption and right data generate of Purpose algorithm able want Decrypt pass need

由于項(xiàng)目的需要,要寫一個(gè)能生成“授權(quán)碼”的類(授權(quán)碼主要包含項(xiàng)目使用的到期時(shí)間),生成的授權(quán)碼將會(huì)寫入到一個(gè)文件當(dāng)中,每當(dāng)項(xiàng)目運(yùn)行的時(shí)候,會(huì)自動(dòng)讀取出文件中的密文,然后使用唯一的“密鑰”來調(diào)用某個(gè)函數(shù),對(duì)密文進(jìn)行解密,從中解讀出項(xiàng)目的使用到期時(shí)間。
之前,自己有先試著寫了下,主要是base64+md5+反轉(zhuǎn)字符串。算法太過簡(jiǎn)單,很容易被破解,而且也沒有能過做到“密鑰”在加解密中的重要性,故而舍之。
后來,查找了相關(guān)資料,發(fā)現(xiàn),原來PHP中內(nèi)置了一個(gè)功能強(qiáng)大的函數(shù)庫,即Mcrypt。
其實(shí),mcrypt本身就提供了強(qiáng)大的加密解密方法,并且支持很多流行的公開的加密算法,如DES, TripleDES, Blowfish (默認(rèn)), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB。
  這里簡(jiǎn)單的引用下百度百科關(guān)于“加密算法”的解釋:
  數(shù)據(jù)加密的基本過程就是對(duì)原來為明文的文件或數(shù)據(jù)按某種算法進(jìn)行處理,使其成為不可讀的一段代碼,通常稱為“密文”,使其只能在輸入相應(yīng)的密鑰之后才能顯示出本來內(nèi)容,通過這樣的途徑來達(dá)到保護(hù)數(shù)據(jù)不被非法人竊取、閱讀的目的。 該過程的逆過程為解密,即將該編碼信息轉(zhuǎn)化為其原來數(shù)據(jù)的過程。
  加密技術(shù)通常分為兩大類:“對(duì)稱式”和“非對(duì)稱式”。
  對(duì)稱式加密就是加密和解密使用同一個(gè)密鑰,通常稱之為“Session Key ”這種加密技術(shù)目前被廣泛采用,如美國政府所采用的DES加密標(biāo)準(zhǔn)就是一種典型的“對(duì)稱式”加密法,它的Session Key長(zhǎng)度為56Bits。
  非對(duì)稱式加密就是加密和解密所使用的不是同一個(gè)密鑰,通常有兩個(gè)密鑰,稱為“公鑰”和“私鑰”,它們兩個(gè)必需配對(duì)使用,否則不能打開加密文件。這里的“公鑰”是指可以對(duì)外公布的,“私鑰”則不能,只能由持有人一個(gè)人知道。它的優(yōu)越性就在這里,因?yàn)閷?duì)稱式的加密方法如果是在網(wǎng)絡(luò)上傳輸加密文件就很難把密鑰告訴對(duì)方,不管用什么方法都有可能被別竊聽到。而非對(duì)稱式的加密方法有兩個(gè)密鑰,且其中的“公鑰”是可以公開的,也就不怕別人知道,收件人解密時(shí)只要用自己的私鑰即可以,這樣就很好地避免了密鑰的傳輸安全性問題。
  前面提到過,mcrypt支持多種國際公開的算法,我在這次的項(xiàng)目中使用的是DES算法,DES(Data Encryption Standard),這是一個(gè)對(duì)稱算法,速度較快,適用于加密大量數(shù)據(jù)的場(chǎng)合。
接下來我簡(jiǎn)要的說明下加密類中會(huì)使用到的幾個(gè)函數(shù)。

--------------------------------------------------------------------------------
resource mcrypt_module_open ( string $algorithm , string $algorithm_directory , string $mode , string $mode_directory )
參數(shù)$algorithm:要使用的算法,可以通過函數(shù)mcrypt_list_algorithms()來查看所有支持的算法名稱
參數(shù)$ mode:要使用哪種模式,同樣,可以內(nèi)置函數(shù)mcrypt_list_algorithms()來查看所有支持的模式

--------------------------------------------------------------------------------
int mcrypt_enc_get_iv_size ( resource $td )
該函數(shù)將返回使用的算法的初始化向量(IV)的大?。粗悬c(diǎn)抽象),如果IV在算法中被忽略的話講返回0。
參數(shù)$td就是使用mcrypt_module_open函數(shù)的返回值。

--------------------------------------------------------------------------------
string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )
該函數(shù)會(huì)創(chuàng)建一個(gè)初始化向量(IV)
參數(shù):
$source可以使MCRYPT_RAND,MCRYPT_DEV_RANDOM,
MCRYPT_DEV_URANDOM
注意:PHP5.3.0以上的版本,只支持MCRYPT_RAND
返回值:
成功,則返回一個(gè)字符串型的初始向量,失敗,則返回False

--------------------------------------------------------------------------------
int mcrypt_enc_get_key_size ( resource $td )
該函數(shù)能夠取得當(dāng)前算法所支持的最大的密鑰長(zhǎng)度(以字節(jié)計(jì)算)
int mcrypt_generic_init ( resource $td , string $key , string $iv )
調(diào)用mcrypt_generic() or mdecrypt_generic()之前,首先需要調(diào)用該函數(shù),該函數(shù)能夠幫我們初始化緩沖區(qū),用以存放加密數(shù)據(jù)。
參數(shù)$key:密鑰長(zhǎng)度,記住,當(dāng)前$key的值,要比函數(shù)mcrypt_enc_get_key_size()返回的值小
問題:$key的值,越大越好嗎?有同學(xué)會(huì)的,幫忙解答下。

--------------------------------------------------------------------------------
string mcrypt_generic ( resource $td , string $data )
完成了前面的工作之后,就可以調(diào)用該函數(shù)用以加密數(shù)據(jù)了。
參數(shù)$data:要加密的數(shù)據(jù)內(nèi)容
返回值:返回加密后的密文

--------------------------------------------------------------------------------
bool mcrypt_generic_deinit ( resource $td )
該函數(shù)能夠幫我們卸載當(dāng)前使用的加密模塊。
返回值
成功時(shí)返回 TRUE, 或者在失敗時(shí)返回 FALSE.

--------------------------------------------------------------------------------
string mdecrypt_generic ( resource $td , string $data )
該函數(shù)能夠用來解密數(shù)據(jù)。
注意:解密后的數(shù)據(jù)可能比實(shí)際上的更長(zhǎng),可能會(huì)有后續(xù)的\0,需去掉

--------------------------------------------------------------------------------
bool mcrypt_module_close ( resource $td )
關(guān)閉指定的加密模塊資源句柄
返回值
成功時(shí)返回 TRUE, 或者在失敗時(shí)返回 FALSE.

--------------------------------------------------------------------------------
貼上代碼:

復(fù)制代碼 代碼如下:


class authCode {
public $ttl;//到期時(shí)間 時(shí)間格式:20120101(年月日)
public $key_1;//密鑰1
public $key_2;//密鑰2
public $td;
public $ks;//密鑰的長(zhǎng)度
public $iv;//初始向量
public $salt;//鹽值(某個(gè)特定的字符串)
public $encode;//加密后的信息
public $return_array = array(); // 返回帶有MAC地址的字串?dāng)?shù)組
public $mac_addr;//mac地址
public $filepath;//保存密文的文件路徑
public function __construct(){
//獲取物理地址
$this->mac_addr=$this->getmac(PHP_OS);
$this->filepath="./licence.txt";
$this->ttl="20120619";//到期時(shí)間
$this->salt="~!@#$";//鹽值,用以提高密文的安全性
// echo "

".print_r(mcrypt_list_algorithms ())."
";
// echo "
".print_r(mcrypt_list_modes())."
";
}
/**
* 對(duì)明文信息進(jìn)行加密
* @param $key 密鑰
*/
public function encode($key) {
$this->td = mcrypt_module_open(MCRYPT_DES,'','ecb',''); //使用MCRYPT_DES算法,ecb模式
$size=mcrypt_enc_get_iv_size($this->td);//設(shè)置初始向量的大小
$this->iv = mcrypt_create_iv($size, MCRYPT_RAND);//創(chuàng)建初始向量
$this->ks = mcrypt_enc_get_key_size($this->td);//返回所支持的最大的密鑰長(zhǎng)度(以字節(jié)計(jì)算)
$this->key_1 = substr(md5(md5($key).$this->salt),0,$this->ks);
mcrypt_generic_init($this->td, $this->key_1, $this->iv); //初始處理
//要保存到明文
$con=$this->mac_addr.$this->ttl;
//加密
$this->encode = mcrypt_generic($this->td, $con);
//結(jié)束處理
mcrypt_generic_deinit($this->td);
//將密文保存到文件中
$this->savetofile();
}
/**
* 對(duì)密文進(jìn)行解密
* @param $key 密鑰
*/
public function decode($key) {
try {
if (!file_exists($this->filepath)){
throw new Exception("授權(quán)文件不存在");
}else{//如果授權(quán)文件存在的話,則讀取授權(quán)文件中的密文
$fp=fopen($this->filepath,'r');
$secret=fread($fp,filesize($this->filepath));
$this->key_2 = substr(md5(md5($key).$this->salt),0,$this->ks);
//初始解密處理
mcrypt_generic_init($this->td, $this->key_2, $this->iv);
//解密
$decrypted = mdecrypt_generic($this->td, $secret);
//解密后,可能會(huì)有后續(xù)的\0,需去掉
$decrypted=trim($decrypted) . "\n";
//結(jié)束
mcrypt_generic_deinit($this->td);
mcrypt_module_close($this->td);
return $decrypted;
}
}catch (Exception $e){
echo $e->getMessage();
}
}
/**
* 將密文保存到文件中
*/
public function savetofile(){
try {
$fp=fopen($this->filepath,'w+');
if (!$fp){
throw new Exception("文件操作失敗");
}
fwrite($fp,$this->encode);
fclose($fp);
}catch (Exception $e){
echo $e->getMessage();
}
}
/**
* 取得服務(wù)器的MAC地址
*/
public function getmac($os_type){
switch ( strtolower($os_type) ){
case "linux":
$this->forLinux();
break;
case "solaris":
break;
case "unix":
break;
case "aix":
break;
default:
$this->forWindows();
break;
}
$temp_array = array();
foreach( $this->return_array as $value ){
if (preg_match("/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i",$value,$temp_array )){
$mac_addr = $temp_array[0];
break;
}
}
unset($temp_array);
return $mac_addr;
}
/**
* windows服務(wù)器下執(zhí)行ipconfig命令
*/
public function forWindows(){
@exec("ipconfig /all", $this->return_array);
if ( $this->return_array )
return $this->return_array;
else{
$ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe";
if ( is_file($ipconfig) )
@exec($ipconfig." /all", $this->return_array);
else
@exec($_SERVER["WINDIR"]."\system\ipconfig.exe /all", $this->return_array);
return $this->return_array;
}
}
/**
* Linux服務(wù)器下執(zhí)行ifconfig命令
*/
public function forLinux(){
@exec("ifconfig -a", $this->return_array);
return $this->return_array;
}
}
$code=new authCode();
//加密
$code->encode("~!@#$%^");
//解密
echo $code->decode("~!@#$%^");
?>

原創(chuàng)文章:WEB開發(fā)_小飛
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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 to get the current session ID in PHP? How to get the current session ID in PHP? Jul 13, 2025 am 03:02 AM

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.

PHP get substring from a string PHP get substring from a string Jul 13, 2025 am 02:59 AM

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.

How do you perform unit testing for php code? How do you perform unit testing for php code? Jul 13, 2025 am 02:54 AM

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

How to split a string into an array in PHP How to split a string into an array in PHP Jul 13, 2025 am 02:59 AM

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: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

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.

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

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)

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

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

How to pass a session variable to another page in PHP? How to pass a session variable to another page in PHP? Jul 13, 2025 am 02:39 AM

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

See all articles