search
HomeBackend DevelopmentPHP TutorialAnalysis of various encryption technologies and code examples in PHP

对称加密(也叫私钥加密)指加密和解密使用相同密钥的加密算法。有时又叫传统密码算法,就是加密密钥能够从解密密钥中推算出来,同时解密密钥也可以 从加密密钥中推算出来。而在大多数的对称算法中,加密密钥和解密密钥是相同的,所以也称这种加密算法为秘密密钥算法或单密钥算法。

信息加密技术的分类

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

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

MD5

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

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

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

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

Crypt

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

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

<?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还有多种盐值加密支持,详见手册 
 
Sha1加密: 
 
string sha1 ( string $str [, bool $raw_output = false ]); //跟md5很像,不同的是sha1()默认情况下返回40个字符的散列值,传入参数性质一样,
第一个为加密的字符串,第二个为raw_output的布尔值,默认为false,如果设置为true,sha1()则会返回原始的20 位原始格式报文摘要 
<?php 
$my_intro="zhouxiaogang"; 
echo sha1($my_intro); // b6773e8c180c693d9f875bcf77c1202a243e8594 
echo "<hr>"; 
//当然,可以将多种加密算法混合使用 
echo md5(sha1($my_intro)); 
//输出:54818bd624d69ac9a139bf92251e381d 
//这种方式的双重加密也可以提高数据的安全性


非对称加密

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

Analysis of various encryption technologies and code examples in PHP

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

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

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

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

在传输过程中,即使攻击者截获了传输的密文,并得到了乙的公钥,也无法破解密文,因为只有乙的私钥才能解密密文

同样,如果乙要回复加密信息给甲,那么需要甲先公布甲的公钥给乙用于加密,甲自己保存甲的私钥用于解密。

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

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

<?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 (emptyempty($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; 
?>

对称加密算法

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

对称加密的常用算法有: DES算法,3DES算法,TDEA算法,Blowfish算法,RC5算法,IDEA算法。
在PHP中也有封装好的对称加密函数

Urlencode/Urldecode 
 
string urlencode ( string $str ) 
/* 
1. 一个参数,传入要加密的字符串(通常应用于对URL的加密) 
2. urlencode为双向加密,可以用urldecode来加密(严格意义上来说,不算真正的加密,更像是一种编码方式) 
3. 返回字符串,此字符串中除了 -_. 之外的所有非字母数字字符都将被替换成百分号(%)后跟两位十六进制数,空格则编码为加号(+)。 
*/

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

<?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"; 
?> 
 
常见的urlencode()的转换字符 
 
?=> %3F 
= => %3D 
% => %25 
& => %26 
\ => %5C 
 
base64 
 
string base64_decode ( string $encoded_data ) 
 
  base64_encode()接受一个参数,也就是要编码的数据(这里不说字符串,是因为很多时候base64用来编码图片) 
 
  base64_encode()为双向加密,可用base64_decode()来解密 
 
$data=file_get_contents($filename); 
echo base64_encode($data); 
/*然后你查看网页源码就会得到一大串base64的字符串, 
再用base64_decode()还原就可以得到图片。这也可以作为移动端上传图片的处理方案之一(但是不建议这样做哈) 
*/

?>

严格的来说..这两个函数其实不算是加密,更像是一种格式的序列化
以下是我们PHP程序中常用到的对称加密算法
discuz经典算法

<?php 
function 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));  
  }  
}

加解密函数encrypt()

<?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)); 
  } 
} 
?>

 以上就是PHP中的多种加密技术及代码示例解析 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor