php中加密解密DES類的簡單使用方法示例
本文實例講述了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_proWWWdesDES5.php on line 2
Fatal error: Uncaught Error: Call to undefined function mcrypt_get_block_size() in D:phpstudy_proWWWdesDES5.php:19 Stack trace: #0 D:phpstudy_proWWWdes1.php(10): DES5->encrypt(’podsmia’) #1 {main} thrown in D:phpstudy_proWWWdesDES5.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); }}
PS:關于加密解密感興趣的朋友還可以參考本站在線工具:
在線DES加密/解密工具http://tools.jb51.net/password/des_encode
MD5在線加密工具:http://tools.jb51.net/password/CreateMD5Password
在線散列/哈希算法加密工具:http://tools.jb51.net/password/hash_encrypt
在線MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:http://tools.jb51.net/password/hash_md5_sha
在線sha1/sha224/sha256/sha384/sha512加密工具:http://tools.jb51.net/password/sha_encode
更多關于PHP相關內容感興趣的讀者可查看本站專題:《php加密方法總結》、《PHP編碼與轉碼操作技巧匯總》、《PHP數學運算技巧總結》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《PHP數據結構與算法教程》、《php程序設計算法總結》及《php正則表達式用法總結》
希望本文所述對大家PHP程序設計有所幫助。
相關文章:
