Table of Contents
MD5
Crypt
Sha1加密:
Urlencode/Urldecode
base64
discuz经典算法
加解密函数encrypt()
Home Backend Development PHP Tutorial An introduction to information encryption technology in PHP

An introduction to information encryption technology in PHP

Jul 10, 2018 pm 04:52 PM

这篇文章主要介绍了关于对于PHP中信息加密技术的介绍,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

单项散列加密技术(不可逆的加密)

属于摘要算法,不是一种加密算法,作用是把任意长的输入字符串变化成固定长的输出串的一种函数

MD5

1

string md5 ( string $str [, bool $raw_output = false ] ); //MD5加密,输入任意长度字符串返回一个唯一的32位字符

Copy after login

md5()为单向加密,没有逆向解密算法,但是还是可以对一些常见的字符串通过收集,枚举,碰撞等方法破解;所以为了让其破解起来更麻烦一些,所以我们一般加一点盐值(salt)并双重MD5;

1

md5(md5($password).'sdva');

Copy after login

sdva就是盐值,该盐值应该是随机的,比如md5常用在密码加密上,所以在注册的时候我会随机生成这个字符串,然后通过上面的方法来双重加密一下;

Crypt

很少看到有人用这个函数,如果要用的话有可能是用在对称或非对称的算法里面,了解一下既可;

1

string crypt ( string $str [, string $salt ] ) //第一个为需要加密的字符串,第二个为盐值(就是加密干扰值,如果没有提供,则默认由PHP自动生成);返回散列后的字符串或一个少于 13 字符的字符串,后者为了区别盐值。

Copy after login

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<?php

$password=&#39;testtest.com&#39;;

echo crypt($password);

//输出:$1$DZ3.QX2.$CQZ8I.OfeepKYrWp0oG8L1

/*第二个$与第三个$之间的八个字符是由PHP生成的,每刷新一次就变一次

*/

echo "<hr>";

  

echo crypt($password,"testtest");

//输出:tesGeyALKYm3A

//当我们要加自定义的盐值时,如例子中的testtest作为第二个参数直接加入, 超出两位字符的会截取前两位

echo "<hr>";

  

echo  crypt($password,&#39;$1$testtest$&#39;);

//输出:$1$testtest$DsiRAWGTHiVH3O0HSHGoL1

/*crypt加密函数有多种盐值加密支持,以上例子展示的是MD5散列作为盐值,该方式下

盐值以$1$$的形式加入,如例子中的testtest加在后两个$符之间,

超出八位字符的会截取前八位,总长为12位;crypt默认就是这种形式。

*/

echo "<hr>";

//crypt还有多种盐值加密支持,详见手册

Copy after login

Sha1加密:

1

string sha1 ( string $str [, bool $raw_output = false ]); //跟md5很像,不同的是sha1()默认情况下返回40个字符的散列值,传入参数性质一样,第一个为加密的字符串,第二个为raw_output的布尔值,默认为false,如果设置为true,sha1()则会返回原始的20 位原始格式报文摘要

Copy after login

1

2

3

4

5

6

7

8

<?php

$my_intro="zhouxiaogang";

echo sha1($my_intro); // b6773e8c180c693d9f875bcf77c1202a243e8594

echo "<hr>";

//当然,可以将多种加密算法混合使用

echo md5(sha1($my_intro));

//输出:54818bd624d69ac9a139bf92251e381d

//这种方式的双重加密也可以提高数据的安全性

Copy after login
非对称加密
Copy after login

非对称加密算法需要两个密钥来进行加密和解密,这两个秘钥是公开密钥(public key,简称公钥)和私有密钥(private key,简称私钥);

An introduction to information encryption technology in PHP

如图所示,甲乙之间使用非对称加密的方式完成了重要信息的安全传输。

  1. 乙方生成一对密钥(公钥和私钥)并将公钥向其它方公开。

  2. 得到该公钥的甲方使用该密钥对机密信息进行加密后再发送给乙方。

  3. 乙方再用自己保存的另一把专用密钥(私钥)对加密后的信息进行解密。乙方只能用其专用密钥(私钥)解密由对应的公钥加密后的信息。

在传输过程中,即使攻击者截获了传输的密文,并得到了乙的公钥,也无法破解密文,因为只有乙的私钥才能解密密文
同样,如果乙要回复加密信息给甲,那么需要甲先公布甲的公钥给乙用于加密,甲自己保存甲的私钥用于解密。

在非对称加密中使用的主要算法有:RSA、Elgamal、背包算法、Rabin、D-H、ECC(椭圆曲线加密算法)等。其中我们最见的算法是RSA算法

以下是从网上摘抄的一段PHP通过openssl实现非对称加密的算法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

<?php

/**

 * 使用openssl实现非对称加密

 * @since 2010-07-08

 */

class Rsa {

    /**

     * private key

     */

    private $_privKey;

    /**

     * public key

     */

    private $_pubKey;

    /**

     * the keys saving path

     */

    private $_keyPath;

    /**

     * the construtor,the param $path is the keys saving path

     */

    public function __construct($path) {

        if (empty($path) || !is_dir($path)) {

            throw new Exception(&#39;Must set the keys save path&#39;);

        }

        $this->_keyPath = $path;

    }

    /**

     * create the key pair,save the key to $this->_keyPath

     */

    public function createKey() {

        $r = openssl_pkey_new();

        openssl_pkey_export($r, $privKey);

        file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . &#39;priv.key&#39;, $privKey);

        $this->_privKey = openssl_pkey_get_public($privKey);

        $rp = openssl_pkey_get_details($r);

        $pubKey = $rp[&#39;key&#39;];

        file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . &#39;pub.key&#39;, $pubKey);

        $this->_pubKey = openssl_pkey_get_public($pubKey);

    }

    /**

     * setup the private key

     */

    public function setupPrivKey() {

        if (is_resource($this->_privKey)) {

            return true;

        }

        $file = $this->_keyPath . DIRECTORY_SEPARATOR . &#39;priv.key&#39;;

        $prk = file_get_contents($file);

        $this->_privKey = openssl_pkey_get_private($prk);

        return true;

    }

    /**

     * setup the public key

     */

    public function setupPubKey() {

        if (is_resource($this->_pubKey)) {

            return true;

        }

        $file = $this->_keyPath . DIRECTORY_SEPARATOR . &#39;pub.key&#39;;

        $puk = file_get_contents($file);

        $this->_pubKey = openssl_pkey_get_public($puk);

        return true;

    }

    /**

     * encrypt with the private key

     */

    public function privEncrypt($data) {

        if (!is_string($data)) {

            return null;

        }

        $this->setupPrivKey();

        $r = openssl_private_encrypt($data, $encrypted, $this->_privKey);

        if ($r) {

            return base64_encode($encrypted);

        }

        return null;

    }

    /**

     * decrypt with the private key

     */

    public function privDecrypt($encrypted) {

        if (!is_string($encrypted)) {

            return null;

        }

        $this->setupPrivKey();

        $encrypted = base64_decode($encrypted);

        $r = openssl_private_decrypt($encrypted, $decrypted, $this->_privKey);

        if ($r) {

            return $decrypted;

        }

        return null;

    }

    /**

     * encrypt with public key

     */

    public function pubEncrypt($data) {

        if (!is_string($data)) {

            return null;

        }

        $this->setupPubKey();

        $r = openssl_public_encrypt($data, $encrypted, $this->_pubKey);

        if ($r) {

            return base64_encode($encrypted);

        }

        return null;

    }

    /**

     * decrypt with the public key

     */

    public function pubDecrypt($crypted) {

        if (!is_string($crypted)) {

            return null;

        }

        $this->setupPubKey();

        $crypted = base64_decode($crypted);

        $r = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey);

        if ($r) {

            return $decrypted;

        }

        return null;

    }

    public function __destruct() {

        @fclose($this->_privKey);

        @fclose($this->_pubKey);

    }

}

//以下是一个简单的测试demo,如果不需要请删除

$rsa = new Rsa(&#39;ssl-key&#39;);

//私钥加密,公钥解密

echo &#39;source:我是老鳖<br />&#39;;

$pre = $rsa->privEncrypt(&#39;我是老鳖&#39;);

echo &#39;private encrypted:<br />&#39; . $pre . &#39;<br />&#39;;

$pud = $rsa->pubDecrypt($pre);

echo &#39;public decrypted:&#39; . $pud . &#39;<br />&#39;;

//公钥加密,私钥解密

echo &#39;source:干IT的<br />&#39;;

$pue = $rsa->pubEncrypt(&#39;干IT的&#39;);

echo &#39;public encrypt:<br />&#39; . $pue . &#39;<br />&#39;;

$prd = $rsa->privDecrypt($pue);

echo &#39;private decrypt:&#39; . $prd;

?>

Copy after login

对称加密(也叫私钥加密)指加密和解密使用相同密钥的加密算法。有时又叫传统密码算法,就是加密密钥能够从解密密钥中推算出来,同时解密密钥也可以从加密密钥中推算出来。而在大多数的对称算法中,加密密钥和解密密钥是相同的,所以也称这种加密算法为秘密密钥算法或单密钥算法。它要求发送方和接收方在安全通信之前,商定一个密钥。对称算法的安全性依赖于密钥,泄漏密钥就意味着任何人都可以对他们发送或接收的消息解密,所以密钥的保密性对通信性至关重要。

对称加密的常用算法有: DES算法,3DES算法,TDEA算法,Blowfish算法,RC5算法,IDEA算法

在PHP中也有封装好的对称加密函数

Urlencode/Urldecode

1

2

3

4

5

6

string urlencode ( string $str )

/*

1. 一个参数,传入要加密的字符串(通常应用于对URL的加密)

2. urlencode为双向加密,可以用urldecode来加密(严格意义上来说,不算真正的加密,更像是一种编码方式)

3. 返回字符串,此字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。

*/

Copy after login

通过Urlencode函数解决链接中带有&字符引起的问题:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?php

$pre_url_encode="zhougang.com?username=zhougang&password=zhou"; //在实际开发中,我们很多时候要构造这种URL,这是没有问题的

$url_decode    ="zhougang.com?username=zhou&gang&password=zhou";//但是这种情况下用$_GET()来接受是会出问题的;

/*

Array

(

  [username] => zhou

  [gang] =>

  [password] => zhou

)

 */

  

  

//如下解决问题:

$username="zhou&gang";

$url_decode="zhougang.com?username=".urlencode($username)."&password=zhou";

?>

Copy after login

常见的urlencode()的转换字符

?=> %3F
= => %3D
% => %25
& => %26
\ => %5C
Copy after login

base64

string base64_decode ( string $encoded_data )
Copy after login
  1. base64_encode()接受一个参数,也就是要编码的数据(这里不说字符串,是因为很多时候base64用来编码图片)

  2. base64_encode()为双向加密,可用base64_decode()来解密

1

2

3

4

5

$data=file_get_contents($filename);

echo base64_encode($data);

/*然后你查看网页源码就会得到一大串base64的字符串,

再用base64_decode()还原就可以得到图片。这也可以作为移动端上传图片的处理方案之一(但是不建议这样做哈)

*/

Copy after login

严格的来说..这两个函数其实不算是加密,更像是一种格式的序列化

以下是我们PHP程序中常用到的对称加密算法

discuz经典算法

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

<?phpfunction authcode($string, $operation = &#39;DECODE&#39;, $key = &#39;&#39;, $expiry = 0) {  

    // 动态密匙长度,相同的明文会生成不同密文就是依靠动态密匙  

    $ckey_length = 4;  

        

    // 密匙  

    $key = md5($key ? $key : $GLOBALS[&#39;discuz_auth_key&#39;]);  

        

    // 密匙a会参与加解密  

    $keya = md5(substr($key, 0, 16));  

    // 密匙b会用来做数据完整性验证  

    $keyb = md5(substr($key, 16, 16));  

    // 密匙c用于变化生成的密文  

    $keyc = $ckey_length ? ($operation == &#39;DECODE&#39; ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : &#39;&#39;;  

    // 参与运算的密匙  

    $cryptkey = $keya.md5($keya.$keyc);  

    $key_length = strlen($cryptkey);  

    // 明文,前10位用来保存时间戳,解密时验证数据有效性,10到26位用来保存$keyb(密匙b), //解密时会通过这个密匙验证数据完整性  

    // 如果是解码的话,会从第$ckey_length位开始,因为密文前$ckey_length位保存 动态密匙,以保证解密正确  

    $string = $operation == &#39;DECODE&#39; ? base64_decode(substr($string, $ckey_length)) :  sprintf(&#39;%010d&#39;, $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;  

    $string_length = strlen($string);  

    $result = &#39;&#39;;  

    $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;  

        $tmp = $box[$a];  

        $box[$a] = $box[$j];  

        $box[$j] = $tmp;  

        // 从密匙簿得出密匙进行异或,再转成字符  

        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));  

    }  

    if($operation == &#39;DECODE&#39;) { 

        // 验证数据有效性,请看未加密明文的格式  

        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && 

substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {  

            return substr($result, 26);  

        } else {  

            return &#39;&#39;;  

        }  

    } else {  

        // 把动态密匙保存在密文里,这也是为什么同样的明文,生产不同密文后能解密的原因  

        // 因为加密后的密文可能是一些特殊字符,复制过程可能会丢失,所以用base64编码  

        return $keyc.str_replace(&#39;=&#39;, &#39;&#39;, base64_encode($result));  

    }  

}

Copy after login

加解密函数encrypt()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<?php//$string:需要加密解密的字符串;$operation:判断是加密还是解密,E表示加密,D表示解密;$key:密匙function encrypt($string,$operation,$key=&#39;&#39;){

    $key=md5($key);

    $key_length=strlen($key);

      $string=$operation==&#39;D&#39;?base64_decode($string):substr(md5($string.$key),0,8).$string;

    $string_length=strlen($string);

    $rndkey=$box=array();

    $result=&#39;&#39;;

    for($i=0;$i<=255;$i++){

           $rndkey[$i]=ord($key[$i%$key_length]);

        $box[$i]=$i;

    }

    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;

        $tmp=$box[$a];

        $box[$a]=$box[$j];

        $box[$j]=$tmp;

        $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));

    }

    if($operation==&#39;D&#39;){

        if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){

            return substr($result,8);

        }else{

            return&#39;&#39;;

        }

    }else{

        return str_replace(&#39;=&#39;,&#39;&#39;,base64_encode($result));

    }

}?>

Copy after login

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

如何解决php在foreach循环后留下的数组引用问题

关于如何导出mongo库到本地的问题解决

The above is the detailed content of An introduction to information encryption technology in PHP. For more information, please follow other related articles on the PHP Chinese website!

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles