当前位置: 首页 > 工具软件 > sign > 使用案例 >

Sign签名生成与校验

傅正豪
2023-12-01

参数说明:

from 接口发起方标识,由管理员分配
secret 密钥,由管理员分配
sign 签名
timestamp 时间戳 s (用于校验签名有效期)

sign算法;
1.对所有参数(此时不含sign参数)升序排列得出arrarg
2.把arrarg的值以’&’拼接成一个字符串得出strarg
3.secret.’&’.strarg.’&’.secret得出sign

<?php
defined('BASEPATH') OR exit('No direct script access allowed');


/**
 * 发起方 校验类
 */
class Sign {


    const TIME = 'timestamp';
    const FROM = 'from';
    const SIGN = 'sign';

    const TIMEOUT = 30; // 签名有效期 s

    private $ci;
    private $froms;


    public function __construct()
    {
        $this->ci =& get_instance();
        $this->froms = $this->ci->config->item('api_froms');
    }


    /**
     * [create 生成签名]
     * @param  [array] $args [参数列表]
     * @param  [string] $secret [密钥]
     * @return [string] sign
     */
    public function create($args,$secret)
    {
        if(isset($args[self::SIGN]))
        {
            unset($args[self::SIGN]);
        }
        if(!is_array($args))
        {
            return FALSE;
        }
        else
        {
            ksort($args);
            $strArgs = implode('&', $args);
            return md5($secret.'&'.$strArgs.'&'.$secret);
        }
    }

    /**
     * [valid 校验请求]
     * @param  string $method [调用方式]
     * @return [array]
     */
    public function valid($data)
    {
        $err = -2;
        $msg = 'falid';
        if( FALSE === $secret=$this->checkFrom($data) )
        {
            $msg = 'the from is not defined';
        }
        elseif(FALSE === $this->checkTime($data))
        {
            $msg = 'the sign is overdue';
        }
        elseif(FALSE === $this->checkSign($data,$secret))
        {
            $msg = 'the sign is wrong';
        }
        else
        {
            $err = 2;
            $msg = 'ok';
        }
        return array('err'=>$err,'msg'=>$msg);
    }

    private function checkSign($data,$secret)
    {
        $sign = isset($data[self::SIGN]) ? $data[self::SIGN] : FALSE;
        if(!$sign )
        {
            return FALSE;
        }
        elseif($sign != $this->create($data,$secret))
        {
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    private function checkTime($data)
    {
        if(! isset($data[self::TIME]))
        {
            return FALSE;
        }
        elseif( self::TIMEOUT < intval(time()-$data[self::TIME]) )
        {
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

    private function checkFrom($data)
    {
        if( ! isset($this->froms[$data[self::FROM]]) )
        {
            return FALSE;
        }
        else
        {
            return $this->froms[$data[self::FROM]];
        }
    }

}
 类似资料: