php防止篡改数据 hash hamc
hmac.class.php
class Hmac{ function __construct($key, $method = 'md5') { if (!in_array($method, ['sha1', 'md5'])) { die('Unsupported hash function ' . $method); } $this->_func = $method; if (strlen($key) > 64) { $key = pack('H32', $method($key)); } if (strlen($key) < 64) { $key = str_pad($key, 64, chr(0)); } $this->_ipad = substr($key, 0, 64) ^ str_repeat(chr(0x36), 64); $this->_opad = substr($key, 0, 64) ^ str_repeat(chr(0x5c), 64); } function hash($data) { $func = $this->_func; $inner = pack('H32', $func($this->_ipad . $data)); $digest = $func($this->_opad . $inner); return $digest; } }
加密与解密函数
function create_parameters($array){ $data = ''; $ret = []; foreach ($array as $k=>$v) { $data .= $k . $v; $ret[] = "$k=$v"; } $h = new Hmac('tenghoo888'); $hash = $h->hash($data); $ret[] = "hash=$hash"; return join('&', $ret); } function verify($array) { $data = ''; $ret = []; $hash = $array['hash']; unset($array['hash']); foreach ($array as $k=>$v) { $data .= $k . $v; $ret[] = "$k=$v"; } $h = new Hmac('tenghoo888'); if ($hash != $h->hash($data)) { return false; } return true; }
调用 index.php
$arr = [ 'name'=>'小红' ]; $res = create_parameters($arr); echo '<a href="user.php?'.$res.'">测试</a>';
user.php
$data = $_GET; var_dump(verify($data));