1.hmvc.php 加密类

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/6
 * Time: 9:14
 */
class Crypt_HMVC {
    private $_func = null;
    private $_ipad = null;
    private $_opad = null;
    function Crypt_HMVC($key, $method = 'md5') {
        if(!in_array($method,array('sha1','md5'))) {
            die('unsupport 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;
    }

}

2.测试类 test.php

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/26
 * Time: 14:09
 */
require_once('hmvc.php');

define('SCRIPT_KEY','Professional php5 programing example');
function create_parameters($array) {
    $data = '';
    $ret = array();//用键值构造字符串
    foreach ($array as $key => $val) {
        $data .=$key . $val;
        $ret [] = "$key=$val";

    }
    $h = new Crypt_HMVC(SCRIPT_KEY,'md5');
    $hash = $h->hash($data);
    $ret [] ="hash=$hash";
    return join('&',$ret);
}

echo '<a href="script.php?'. create_parameters(array('cause'=>'vars')) .'">err!</a>';

3.script.php类

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/6
 * Time: 10:02
 */

require_once('hmvc.php');

define('SCRIPT_KEY','Professional php5 programing example');

function create_parameters($array) {
    $data = '';
    $ret = array();

    //把散列放在一个单独的变量里面 并且在数组中注销掉该变量
    $hash = $array['hash'];
    unset( $array['hash']);

    //用键值对构造字符串
    foreach ($array as $key => $val) {
        $data .= $key . $val;
        $ret [] = "$key=$val";
    }

    $h = new Crypt_HMVC(SCRIPT_KEY,'md5');
    if($hash != $h->hash($data)) {
        return false;
    } else {
        return true;
    }
}
$arr = $_GET;

if(!create_parameters($arr)) {
    die('dweep someone tempered with our parameters');
} else {
    echo 'good you are success';
}

运行test.php

结果

good you are success

mmy123456
376 声望17 粉丝

有项目请联系:15201970281(毛毛)