mcrypt_get_block_size — 获得加密算法的分组大小
此函数将在PHP7.1.0以后将被弃用。
1 | int mcrypt_get_block_size ( int $cipher ) |
1 | int mcrypt_get_block_size ( string $cipher , string $mode ) |
第一个原型针对 libmcrypt 2.2.x, 第二个原型针对 libmcrypt 2.4.x 或 2.5.x。
PHP的AES加、解密类:
<?php class Security { public static function encrypt( $input , $key ) { // define ('MCRYPT_RIJNDAEL_128', "rijndael-128");// 16字节,128位 // define ('MCRYPT_MODE_ECB', "ecb");// 常用加密模式 $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB); // 填充空位;pkcs5_pad&pkcs7_pad二者区别不大 $input = Security::pkcs5_pad( $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 ; } /** * $text 加密的字符串 * $blocksize 区块大小,16字节;值为16 */ private static function pkcs5_pad ( $text , $blocksize ) { $pad = $blocksize - ( strlen ( $text ) % $blocksize ); // 使用$pad的ascii码值来填充空位 return $text . str_repeat ( chr ( $pad ), $pad ); } public static function decrypt( $sStr , $sKey ) { $decrypted = mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $sKey , base64_decode ( $sStr ), MCRYPT_MODE_ECB ); $dec_s = strlen ( $decrypted ); $padding = ord( $decrypted [ $dec_s -1]); $decrypted = substr ( $decrypted , 0, - $padding ); return $decrypted ; } } // $key = "1234567891234567"; // $data = '{"user":"1234556789","pwd":"4343434343","tel":"18988888888","realname":"zhangsan"}'; // $value = Security::encrypt($data , $key ); // echo "加密::".$value.'<br/>'; // echo Security::decrypt($value, $key ); |
代码中使用:
/** * 加密、解密 */ function zm_ecrypt() { // 加密、解密 $string = '{"user":"1234556789","pwd":"4343434343","tel":"18988888888","realname":"zhangsan"}' ; vendor( 'encrypt.Security' ) or die ( "方案7引入失败" ); $sec = new \Security(); // 这里对第二个参数key进行了base64_encode加密 $sec_res1 = $sec ->encrypt( $string , "em1hcnRlAzIwMTc5ODc2NTQzMjEwMTIz" ); // 结果转16进制 $sec_res = toHexString( base64_decode ( $sec_res1 )); // 解密 // 先把十六进制转成字符串,然后进行base64_encode $demo = base64_encode (hexToStr( $sec_res )); $sec_dec = $sec ->decrypt( $demo , "em1hcnRlAzIwMTc5ODc2NTQzMjEwMTIz" ); // var_dump("\r\n方案7加密的结果\r\n" . $sec_res); // var_dump("\r\n方案7解密的结果\r\n" . $sec_dec); // return $as_res_encrypt; } |
使用的时候,请注意base64_encode和base64_decode,对key和string是否进行编码。
用到的十六进制与字符串之间的转换:
/** * 十六进制转字符串 * 16进制的转为2进制字符串 * @param 十六进制 $hex * @return string */ function hexToStr( $hex ) { $string = "" ; for ( $i =0; $i < strlen ( $hex )-1; $i +=2) $string .= chr (hexdec( $hex [ $i ]. $hex [ $i +1])); return $string ; } /** * 将$string转换成十六进制 * @param string $string * @return stream */ function toHexString ( $string ){ $buf = "" ; for ( $i = 0; $i < strlen ( $string ); $i ++){ $val = dechex (ord( $string { $i })); if ( strlen ( $val )< 2) $val = "0" . $val ; $buf .= $val ; } return $buf ; } |