Created
September 23, 2015 01:32
-
-
Save GerBawn/3b8fb8a3965d07370c01 to your computer and use it in GitHub Desktop.
des加密
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Created by PhpStorm. | |
* User: tew | |
* Date: 2015/9/23 | |
* Time: 9:32 | |
*/ | |
class mcrypt{ | |
public static $key = '7fdc4b8e'; | |
public static function encode($text){ | |
$result = ""; | |
if(!empty($text)){ | |
$val = self::pad($text); | |
$td = mcrypt_module_open(MCRYPT_DES,'',MCRYPT_MODE_ECB,''); //使用MCRYPT_DES算法,cbc模式 | |
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); | |
mcrypt_generic_init($td,self::$key,$iv); //初始处理 | |
$encrypted = mcrypt_generic($td,$val); //解密 | |
mcrypt_generic_deinit($td); //结束 | |
mcrypt_module_close($td); | |
$result = base64_encode($encrypted); | |
} | |
return $result; | |
} | |
public static function decode($encrypted){ | |
$result = ""; | |
if(!empty($encrypted)){ | |
$encrypted = base64_decode($encrypted); | |
$td = mcrypt_module_open(MCRYPT_DES,'',MCRYPT_MODE_ECB,''); //使用MCRYPT_DES算法,cbc模式 | |
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); | |
mcrypt_generic_init($td,self::$key,$iv); //初始处理 | |
$decrypted = mdecrypt_generic($td, $encrypted); //解密 | |
mcrypt_generic_deinit($td); //结束 | |
mcrypt_module_close($td); | |
$result = self::unpad($decrypted); | |
} | |
return $result; | |
} | |
public static function pad($text,$block = 8){ | |
$pad = $block - (strlen($text) % $block); | |
return $text . str_repeat(chr($pad), $pad); | |
} | |
public static function unpad($text){ | |
$pad = ord($text{strlen($text)-1}); | |
if ($pad > strlen($text)) | |
return $text; | |
if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) | |
return $text; | |
return substr($text, 0, -1 * $pad); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment