Home php教程 php手册 通过PHP的内置函数,通过DES算法对数据加密和解密

通过PHP的内置函数,通过DES算法对数据加密和解密

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

由于项目的需要,要写一个能生成“授权码”的类(授权码主要包含项目使用的到期时间),生成的授权码将会写入到一个文件当中,每当项目运行的时候,会自动读取出文件中的密文,然后使用唯一的“密钥”来调用某个函数,对密文进行解密,从中解读出项目的使用到期时间。
之前,自己有先试着写了下,主要是base64+md5+反转字符串。算法太过简单,很容易被破解,而且也没有能过做到“密钥”在加解密中的重要性,故而舍之。
后来,查找了相关资料,发现,原来PHP中内置了一个功能强大的函数库,即Mcrypt。
其实,mcrypt本身就提供了强大的加密解密方法,并且支持很多流行的公开的加密算法,如DES, TripleDES, Blowfish (默认), 3-WAY, SAFER-SK64, SAFER-SK128, TWOFISH, TEA, RC2 and GOST in CBC, OFB, CFB and ECB。
  这里简单的引用下百度百科关于“加密算法”的解释:
  数据加密的基本过程就是对原来为明文的文件或数据按某种算法进行处理,使其成为不可读的一段代码,通常称为“密文”,使其只能在输入相应的密钥之后才能显示出本来内容,通过这样的途径来达到保护数据不被非法人窃取、阅读的目的。 该过程的逆过程为解密,即将该编码信息转化为其原来数据的过程。
  加密技术通常分为两大类:“对称式”和“非对称式”。
  对称式加密就是加密和解密使用同一个密钥,通常称之为“Session Key ”这种加密技术目前被广泛采用,如美国政府所采用的DES加密标准就是一种典型的“对称式”加密法,它的Session Key长度为56Bits。
  非对称式加密就是加密和解密所使用的不是同一个密钥,通常有两个密钥,称为“公钥”和“私钥”,它们两个必需配对使用,否则不能打开加密文件。这里的“公钥”是指可以对外公布的,“私钥”则不能,只能由持有人一个人知道。它的优越性就在这里,因为对称式的加密方法如果是在网络上传输加密文件就很难把密钥告诉对方,不管用什么方法都有可能被别窃听到。而非对称式的加密方法有两个密钥,且其中的“公钥”是可以公开的,也就不怕别人知道,收件人解密时只要用自己的私钥即可以,这样就很好地避免了密钥的传输安全性问题。
  前面提到过,mcrypt支持多种国际公开的算法,我在这次的项目中使用的是DES算法,DES(Data Encryption Standard),这是一个对称算法,速度较快,适用于加密大量数据的场合。
接下来我简要的说明下加密类中会使用到的几个函数。

--------------------------------------------------------------------------------
resource mcrypt_module_open ( string $algorithm , string $algorithm_directory , string $mode , string $mode_directory )
参数$algorithm:要使用的算法,可以通过函数mcrypt_list_algorithms()来查看所有支持的算法名称
参数$ mode:要使用哪种模式,同样,可以内置函数mcrypt_list_algorithms()来查看所有支持的模式

--------------------------------------------------------------------------------
int mcrypt_enc_get_iv_size ( resource $td )
该函数将返回使用的算法的初始化向量(IV)的大小(看着有点抽象),如果IV在算法中被忽略的话讲返回0。
参数$td就是使用mcrypt_module_open函数的返回值。

--------------------------------------------------------------------------------
string mcrypt_create_iv ( int $size [, int $source = MCRYPT_DEV_RANDOM ] )
该函数会创建一个初始化向量(IV)
参数:
$source可以使MCRYPT_RAND,MCRYPT_DEV_RANDOM,
MCRYPT_DEV_URANDOM
注意:PHP5.3.0以上的版本,只支持MCRYPT_RAND
返回值:
成功,则返回一个字符串型的初始向量,失败,则返回False

--------------------------------------------------------------------------------
int mcrypt_enc_get_key_size ( resource $td )
该函数能够取得当前算法所支持的最大的密钥长度(以字节计算)
int mcrypt_generic_init ( resource $td , string $key , string $iv )
调用mcrypt_generic() or mdecrypt_generic()之前,首先需要调用该函数,该函数能够帮我们初始化缓冲区,用以存放加密数据。
参数$key:密钥长度,记住,当前$key的值,要比函数mcrypt_enc_get_key_size()返回的值小
问题:$key的值,越大越好吗?有同学会的,帮忙解答下。

--------------------------------------------------------------------------------
string mcrypt_generic ( resource $td , string $data )
完成了前面的工作之后,就可以调用该函数用以加密数据了。
参数$data:要加密的数据内容
返回值:返回加密后的密文

--------------------------------------------------------------------------------
bool mcrypt_generic_deinit ( resource $td )
该函数能够帮我们卸载当前使用的加密模块。
返回值
成功时返回 TRUE, 或者在失败时返回 FALSE.

--------------------------------------------------------------------------------
string mdecrypt_generic ( resource $td , string $data )
该函数能够用来解密数据。
注意:解密后的数据可能比实际上的更长,可能会有后续的\0,需去掉

--------------------------------------------------------------------------------
bool mcrypt_module_close ( resource $td )
关闭指定的加密模块资源句柄
返回值
成功时返回 TRUE, 或者在失败时返回 FALSE.

--------------------------------------------------------------------------------
贴上代码:

复制代码 代码如下:


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地址的字串数组
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 ())."
Copy after login
";
// echo "
".print_r(mcrypt_list_modes())."
Copy after login
";
}
/**
* 对明文信息进行加密
* @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);//设置初始向量的大小
$this->iv = mcrypt_create_iv($size, MCRYPT_RAND);//创建初始向量
$this->ks = mcrypt_enc_get_key_size($this->td);//返回所支持的最大的密钥长度(以字节计算)
$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);
//结束处理
mcrypt_generic_deinit($this->td);
//将密文保存到文件中
$this->savetofile();
}
/**
* 对密文进行解密
* @param $key 密钥
*/
public function decode($key) {
try {
if (!file_exists($this->filepath)){
throw new Exception("授权文件不存在");
}else{//如果授权文件存在的话,则读取授权文件中的密文
$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);
//解密后,可能会有后续的\0,需去掉
$decrypted=trim($decrypted) . "\n";
//结束
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();
}
}
/**
* 取得服务器的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服务器下执行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服务器下执行ifconfig命令
*/
public function forLinux(){
@exec("ifconfig -a", $this->return_array);
return $this->return_array;
}
}
$code=new authCode();
//加密
$code->encode("~!@#$%^");
//解密
echo $code->decode("~!@#$%^");
?>

原创文章:WEB开发_小飞
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

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 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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP? Apr 07, 2025 am 12:02 AM

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

See all articles