1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| $str = json_encode(['a' => 1, 'b' => 2]); $Encr = new AesCryptUtil(); $key = 'eeqIYJna6NHfwiqi'; $en1 = $Encr::mcryptEncrypt($str,$key); $en2 = $Encr::opensslEncrypt($str,$key);
$den1= $Encr::mcryptDecrypt($en1,$key); $den2= $Encr::opensslDecrypt($en2,$key); echo "加密前数据:".$str."\r\n"; echo "Encrypt加密后数据:".$en1."\r\n"; echo "Decrypt解密的数据:".$den1."\r\n"; echo "openssl加密后数据:".$en2."\r\n"; echo "openssl解密的数据:".$den2."\r\n";
class AesCryptUtil{
public static function mcryptEncrypt($input, $key) { $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); $input = self::pkcs5Pad($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; }
private static function pkcs5Pad($text, $blocksize) { $pad = $blocksize - (strlen($text) % $blocksize); return $text . str_repeat(chr($pad), $pad); }
public static function mcryptDecrypt($sStr, $sKey) { $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND); $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $sKey, base64_decode($sStr), MCRYPT_MODE_ECB, $iv); $dec_s = strlen($decrypted); $padding = ord($decrypted[$dec_s-1]); $decrypted = substr($decrypted, 0, -$padding); return $decrypted; }
public static function opensslEncrypt($sStr, $sKey, $method = 'AES-128-ECB'){ $str = openssl_encrypt($sStr,$method,$sKey); return $str; }
public static function opensslDecrypt($sStr, $sKey, $method = 'AES-128-ECB'){ $str = openssl_decrypt($sStr,$method,$sKey); return $str; } }
|