Posted in PHP onMarch 26, 2020
本文实例讲述了php中加密解密DES类的简单使用方法。分享给大家供大家参考,具体如下:
在平时的开发工作中,我们经常会对关键字符进行加密,可能为了安全 也可能为了规范,所以要正确使用DES加密解密
代码1:
class DES { var $key; // 密钥 var $iv; // 偏移量 function __construct( $key, $iv=0 ) { $this->key = $key; if( $iv == 0 ) { $this->iv = $key; } else { $this->iv = $iv; // 创建初始向量, 并且检测密钥长度, Windows 平台请使用 MCRYPT_RAND // mcrypt_create_iv ( mcrypt_get_block_size (MCRYPT_DES, MCRYPT_MODE_CBC), MCRYPT_DEV_RANDOM ); } } function encrypt($str) { //加密,返回大写十六进制字符串 $size = mcrypt_get_block_size ( MCRYPT_DES, MCRYPT_MODE_CBC ); $str = $this->pkcs5Pad ( $str, $size ); // bin2hex 把 ASCII 字符的字符串转换为十六进制值 return strtoupper( bin2hex( mcrypt_cbc(MCRYPT_DES, $this->key, $str, MCRYPT_ENCRYPT, $this->iv ) ) ); } function decrypt($str) { //解密 $strBin = $this->hex2bin( strtolower( $str ) ); $str = mcrypt_cbc( MCRYPT_DES, $this->key, $strBin, MCRYPT_DECRYPT, $this->iv ); $str = $this->pkcs5Unpad( $str ); return $str; } function hex2bin($hexData) { $binData = ""; for($i = 0; $i < strlen ( $hexData ); $i += 2) { $binData .= chr ( hexdec ( substr ( $hexData, $i, 2 ) ) ); } return $binData; } function pkcs5Pad($text, $blocksize) { $pad = $blocksize - (strlen ( $text ) % $blocksize); return $text . str_repeat ( chr ( $pad ), $pad ); } function pkcs5Unpad($text) { $pad = ord ( $text {strlen ( $text ) - 1} ); if ($pad > strlen ( $text )) return false; if (strspn ( $text, chr ( $pad ), strlen ( $text ) - $pad ) != $pad) return false; return substr ( $text, 0, - 1 * $pad ); } }
Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; DES5 has a deprecated constructor in D:\phpstudy_pro\WWW\des\DES5.php on line 2
Fatal error: Uncaught Error: Call to undefined function mcrypt_get_block_size() in D:\phpstudy_pro\WWW\des\DES5.php:19 Stack trace: #0 D:\phpstudy_pro\WWW\des\1.php(10): DES5->encrypt('podsmia') #1 {main} thrown in D:\phpstudy_pro\WWW\des\DES5.php on line 19
- mcrypt_cbc 以 CBC 模式加解密数据, 在PHP 5.5.0+被弃用, PHP 7.0.0被移除
- mcrypt_encrypt / mcrypt_decrypt 使用给定参数加密 / 解密, 在PHP 7.1.0+被弃用, 在PHP 7.2.0+被移除
代码2:
class DES7 { //要改的加密, 使用 openssl public function desEncrypt($str,$key) { $iv = $key; $data = openssl_encrypt($str,"DES-CBC",$key,OPENSSL_RAW_DATA,$iv); $data = strtolower(bin2hex($data)); return $data; } //要改的解密 public function desDecrypt($str,$key) { $iv = $key; return openssl_decrypt (hex2bin($str), 'DES-CBC', $key, OPENSSL_RAW_DATA,$iv); } }
php中加密解密DES类的简单使用方法示例
- Author -
OldKind超声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@