Created
April 21, 2018 10:09
-
-
Save komeiji-satori/eb0298dd11fe0d2381890b769f58155f to your computer and use it in GitHub Desktop.
This file contains 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 | |
class MagicCrypt | |
{ | |
public static $iv = ""; | |
public static $encryptKey = ""; | |
public function __construct($key = '', $iv = '') | |
{ | |
$this->key = $key; | |
$this->iv = $iv; | |
} | |
//加密 | |
public static function encrypt($encryptStr) | |
{ | |
$localIV = self::$iv; | |
$encryptKey = self::$encryptKey; | |
//Open module | |
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV); | |
mcrypt_generic_init($module, $encryptKey, $localIV); | |
//Padding | |
$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); | |
$pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad | |
$encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples | |
//encrypt | |
$encrypted = mcrypt_generic($module, $encryptStr); | |
//Close | |
mcrypt_generic_deinit($module); | |
mcrypt_module_close($module); | |
return base64_encode($encrypted); | |
} | |
//解密 | |
public static function decrypt($encryptStr) | |
{ | |
$localIV = self::$iv; | |
$encryptKey = self::$encryptKey; | |
//Open module | |
$module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV); | |
//print "module = $module <br/>" ; | |
mcrypt_generic_init($module, $encryptKey, $localIV); | |
$encryptedData = base64_decode($encryptStr); | |
$encryptedData = mdecrypt_generic($module, $encryptedData); | |
return $encryptedData; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment