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

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

通過PHP的內(nèi)置函數(shù),通過DES算法對數(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

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

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

--------------------------------------------------------------------------------
int mcrypt_enc_get_key_size ( resource $td )
該函數(shù)能夠取得當(dāng)前算法所支持的最大的密鑰長度(以字節(jié)計算)
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:密鑰長度,記住,當(dāng)前$key的值,要比函數(shù)mcrypt_enc_get_key_size()返回的值小
問題:$key的值,越大越好嗎?有同學(xué)會的,幫忙解答下。

--------------------------------------------------------------------------------
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)前使用的加密模塊。
返回值
成功時返回 TRUE, 或者在失敗時返回 FALSE.

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

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

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

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


class authCode {
public $ttl;//到期時間 時間格式:20120101(年月日)
public $key_1;//密鑰1
public $key_2;//密鑰2
public $td;
public $ks;//密鑰的長度
public $iv;//初始向量
public $salt;//鹽值(某個特定的字符串)
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";//到期時間
$this->salt="~!@#$";//鹽值,用以提高密文的安全性
// echo "

".print_r(mcrypt_list_algorithms ())."
";
// echo "
".print_r(mcrypt_list_modes())."
";
}
/**
* 對明文信息進(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);//返回所支持的最大的密鑰長度(以字節(jié)計算)
$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();
}
/**
* 對密文進(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);
//解密后,可能會有后續(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)

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

Bian binance exchange official website login portal Bian binance exchange official website login portal Jun 24, 2025 pm 06:15 PM

Binance is the world's leading cryptocurrency trading platform with excellent security, rich trading varieties and smooth user experience. It adopts a multi-layer security architecture to ensure asset security, provides a variety of transaction types such as spot, leverage, contracts, etc., and has high liquidity to ensure efficient transactions. The login steps include: 1. Visit the official website and check the URL; 2. Click the "Login" button in the upper right corner; 3. Enter the email/mobile phone number and password; 4. Complete security verification such as two-factor verification, SMS or email verification code; 5. Click to log in to complete the operation. The platform also provides Binance Earn, NFT market, Academy and other special features, and reminds users to beware of phishing websites, enable 2FA, understand transaction risks, beware of fraud, and ensure that

How do I use page caching in PHP? How do I use page caching in PHP? Jun 24, 2025 am 12:50 AM

PHP page caching improves website performance by reducing server load and speeding up page loading. 1. Basic file cache avoids repeated generation of dynamic content by generating static HTML files and providing services during the validity period; 2. Enable OPcache to compile PHP scripts into bytecode and store them in memory, improving execution efficiency; 3. For dynamic pages with parameters, they should be cached separately according to URL parameters, and avoid cached user-specific content; 4. Lightweight cache libraries such as PHPFastCache can be used to simplify development and support multiple storage drivers. Combining these methods can effectively optimize the caching strategy of PHP projects.

How to quickly test PHP code snippets? How to quickly test PHP code snippets? Jun 25, 2025 am 12:58 AM

ToquicklytestaPHPcodesnippet,useanonlinePHPsandboxlike3v4l.orgorPHPize.onlineforinstantexecutionwithoutsetup;runcodelocallywithPHPCLIbycreatinga.phpfileandexecutingitviatheterminal;optionallyusephp-rforone-liners;setupalocaldevelopmentenvironmentwith

See all articles