php 中關於AES 的使用 ,被友盟搞死了
阿新 • • 發佈:2019-01-30
function aes128_cbc_encrypt($key, $data, $iv) { if(16 !== strlen($key)) $key = hash('MD5', $key, true); if(16 !== strlen($iv)) $iv = hash('MD5', $iv, true); $padding = 16 - (strlen($data) % 16); $data .= str_repeat(chr($padding), $padding); return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv); } function aes256_cbc_encrypt($key, $data, $iv) { if(32 !== strlen($key)) $key = hash('SHA256', $key, true); if(16 !== strlen($iv)) $iv = hash('MD5', $iv, true); $padding = 16 - (strlen($data) % 16); $data .= str_repeat(chr($padding), $padding); return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv); } function aes128_cbc_decrypt($key, $data, $iv) { if(16 !== strlen($key)) $key = hash('MD5', $key, true); if(16 !== strlen($iv)) $iv = hash('MD5', $iv, true); $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv); $padding = ord($data[strlen($data) - 1]); return substr($data, 0, -$padding); } function aes256_cbc_decrypt($key, $data, $iv) { if(32 !== strlen($key)) $key = hash('SHA256', $key, true); if(16 !== strlen($iv)) $iv = hash('MD5', $iv, true); $data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv); $padding = ord($data[strlen($data) - 1]); return substr($data, 0, -$padding); }
關於加密的demo:
<?php $cipher_list = mcrypt_list_algorithms();//mcrypt支援的加密演算法列表 $mode_list = mcrypt_list_modes(); //mcrypt支援的加密模式列表 // echo strlen('{"source_id": "123312", "source": "qq", "source_name": "hello"}'); function aes256_cbc_encrypt($key, $data, $iv) { if(16 !== strlen($iv)) $iv = substr($iv, 0, 16); $padding = 32 - (strlen($data) % 32); echo "strlen data is",strlen($data); $data .= str_repeat(chr($padding), $padding); echo " strlen data is",strlen($data); return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $data, MCRYPT_MODE_CBC, $iv); } $str_new = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,"273d7e70c2d115e6",'0063{"source_id": "123312", "source": "qq", "source_name": "hello"}' ,MCRYPT_MODE_CBC,'273d7e70c2d115e6')); // echo $str_new,":",strlen($str_new)."\n"; // class A { // public $source_id; // public $source; // public $user_info; // } // class B{ // public $name; // public $gender; // } // $a = new A(); // $a->source_id="12333"; // $a->source = "xinshangyun"; // $b = new B(); // $b->name ="testEncrypt"; // $b->gender = 1; // $a->user_info = $b; // $data = json_encode($a,true); // echo $data."\n"; $raw_data = '{"source_id": "123312", "source": "qq", "source_name": "hello"}'; $raw_len = strlen($raw_data); $body = pack("a{$raw_len}",$raw_data); $head = pack('N',strlen($body)); $data = $head.$raw_data; $str = aes256_cbc_encrypt('273d7e70c2d115e62e0e45656ff82b39',$data ,'273d7e70c2d115e62e0e45656ff82b39'); echo $str."\n"."\n"; echo "\n".base64_encode($str),":",strlen(base64_encode($str)),":",strlen('JIwOfhuwb/7CO6w/ackXW8aYOkP/75LcjmVUOms0bzQZLyZ1aQC8Sf8mJdp40DD3FfNE4aIa6/EgIejLBMi2tMVZXHbuC9ZTHUgMs5gFGcje8L3a2+4S+QRThYIWUQOp'); ?>