Created
May 12, 2015 02:28
-
-
Save guweigang/569d6189e9f86ab21839 to your computer and use it in GitHub Desktop.
AES
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 | |
namespace NCFGroup\Common\Library; | |
/** | |
* AES对称加密封装 (包括base64) | |
* 算法: AES128位 | |
* 模式: ECB | |
* 填充: PKCS5Padding | |
*/ | |
class AesLib | |
{ | |
/** | |
* 加密 (Aes + base64) | |
*/ | |
public static function encode($input, $key) | |
{ | |
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); | |
$input = self::pkcs5Padding($input, $size); | |
$td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, ''); | |
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); | |
mcrypt_generic_init($td, $key, $iv); | |
$data = mcrypt_generic($td, $input); | |
mcrypt_generic_deinit($td); | |
mcrypt_module_close($td); | |
$data = base64_encode($data); | |
return $data; | |
} | |
/** | |
* PKCS5方式填充 | |
*/ | |
private static function pkcs5Padding($text, $blocksize) | |
{ | |
$pad = $blocksize - (strlen($text) % $blocksize); | |
return $text.str_repeat(chr($pad), $pad); | |
} | |
/** | |
* 解密 (base64 + Aes) | |
*/ | |
public static function decode($data, $key) | |
{ | |
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($data), MCRYPT_MODE_ECB); | |
$dec_s = strlen($decrypted); | |
$padding = ord($decrypted[$dec_s - 1]); | |
$decrypted = substr($decrypted, 0, -$padding); | |
return $decrypted; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment