关于接口安全

<?php
header('content-type:text/html;charset=utf-8');
class DES
{


    /**
     * DES加密 (需要打开php.ini的extension=php_mcrypt.dll)
     * @param string $input
     * @param string $key
     * @return string
     */
    public static function encode($input, $key, $iv)
    {


        //填充算法 PKCS7
        $input = DES::addPKCS7Padding($input);


        //打开算法和模式对应的模块  加密算法 3DES 加密模式 CBC
        $td = mcrypt_module_open(MCRYPT_3DES, '', 'cbc', '');


        //设置加密的key 以及初始化向量
        mcrypt_generic_init($td, $key, $iv);


        //加密
        $encrypted_data = mcrypt_generic($td, $input);




        //对加密模块进行清理工作
        mcrypt_generic_deinit($td);


        //关闭加密模块
        mcrypt_module_close($td);




//        var_dump(($encrypted_data) );exit;


        //加加密的数据进行base64编码
        $encode = trim(chop(base64_encode($encrypted_data)));


        return $encode;
    }


    /**
     * DES解密
     * @param string $input
     * @param string $key
     * @return string
     */
    public static function decode($input, $key, $iv)
    {
        //反编码
        $input = trim(chop(base64_decode($input)));


        //打开算法和模式对应的模块  加密算法 3DES 加密模式 CBC
        $td = mcrypt_module_open(MCRYPT_3DES, '', 'cbc', '');


        //设置加密的key 以及初始化向量
        mcrypt_generic_init($td, $key, $iv);


        //解密的数据
        $decrypted_data = mdecrypt_generic($td, $input);


        //对加密模块进行清理工作
        mcrypt_generic_deinit($td);


        //关闭加密模块
        mcrypt_module_close($td);


        //去除 PKCS7 填充
        $decrypted_data = DES::stripPKSC7Padding($decrypted_data);


        return $decrypted_data;
    }


    //PKCS7填充
    private static function addPKCS7Padding($source)
    {
        //获得加密算法的分组大小 8
        $block = mcrypt_get_block_size(MCRYPT_3DES, 'cbc');


        //计算要填充的长度
        $pad = $block - (strlen($source) % $block);


        //填充字符串
        if ($pad <= $block) {


            //chr — 返回指定的字符 ASCII
            $char = chr($pad);


            //填充字符串
            $source .= str_repeat($char, $pad);
        }
        return $source;
    }


    //去除PKCS7的填充
    private static function stripPKSC7Padding($source)
    {
        //获得加密算法的分组大小 8
        $block = mcrypt_get_block_size(MCRYPT_3DES, 'cbc');


        $char = substr($source, -1, 1);


        //返回字符的 ASCII 码值
        $num = ord($char);


        if ($num > 8) {
            return $source;
        }


        $len = strlen($source);
        for ($i = $len - 1; $i >= $len - $num; $i--) {
            if (ord(substr($source, $i, 1)) != $num) {
                return $source;
            }


        }
        $source = substr($source, 0, -$num);


        return $source;
    }
}


function CurlPost($url, $param = null, $timeout = 10)
{




    //初始化curl
    $curl = curl_init();


    curl_setopt($curl, CURLOPT_URL, $url); // 设置请求的路径
    curl_setopt($curl, CURLOPT_POST, 1); //设置POST提交
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //显示输出结果
    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);


    //提交数据
    if (is_array($param)) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($param));
    } else {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
    }


    //执行请求
    $data = $data_str = curl_exec($curl);


    //处理错误
    if ($error = curl_error($curl)) {
        $logdata = array(
            'url' => $url,
            'param' => $param,
            'error' => '<span style="color:red;font-weight: bold">' . $error . '</span>',
        );


        var_dump($logdata);
        exit;
    }




    curl_close($curl);


    //json数据转换为数组
    $data = json_decode($data, true);


    if (!is_array($data)) {
        $data = $data_str;
    }


    return $data;


}


###############################接口加密##################################
$key = 'zhangsan';
$iv = '44542858';

$url = 'http://api.com/account/LoginNew';


$param = [
    'account_name' => 'zhangsan',
    'password' => '123456',
    'status' => 1,
    'session_id'=>'aaaaaaaaaaaaaaa',
    'vcode' => '8888'
];




###############################接口加密##################################

###############################接口签名##################################
#签名算法:1、对请求的原始数据进行排序【按照key进行排序】
#        2、对排序之后的数组进行MD5生成一个签名
#        3、把生成的签名发送到服务端
#        4、服务端进行验签,保证数据在传输的过程中不会被修改
###############################接口签名##################################


###############################接口签名##################################


###############################接口鉴权###################################
#  1、用来验证是否是正常的请求 --- 需要提供参数 appkey 和 appsecret            #
#  2、可以用来保证签名算法的安全性  ----  签名需要加入 appsecret               #
#  3、后期可以用来做接口鉴权                                               #
#######################################################################
//$app_key = md5('likang');
//$app_secret = md5('a123456');
//var_dump($app_secret);
//$param['app_key'] = $app_key;
$param['app_secret'] = $app_secret;
//
//ksort( $param );
//var_dump($param);
//$api_request_arr['sign'] = md5( json_encode($param) . $app_secret );
//
//echo '<pre/>';
//$encode_str = DES::encode( json_encode( $param ) , $key , $iv );
//$api_request_arr['data']= $encode_str;


//print_r( $api_request_arr );
//exit;


###############################接口鉴权##################################


###############################接口防刷##################################
# 1、通过nginx限制
# 2、通过防火墙限制 iptables
# 3、通过程序限制 --  ip黑名单
###############################接口防刷##################################

set_time_limit( 0 );

$api_result = CurlPost( $url , $param );
print_r($api_result) ;
exit;

/**
 * 使用openssl实现非对称加密
 * @since 2010-07-08
 */
class Rsa
{
    /**
     * private key
     */
        private $_privKey;


        /**
         * public key
         */
        private $_pubKey;


        /**
         * the keys saving path
         */
        private $_keyPath;


        /**
         * the construtor,the param $path is the keys saving path
         */
        public function __construct($path)
        {
                if(empty($path) || !is_dir($path)){
                        throw new Exception('Must set the keys save path');
                }


                $this->_keyPath = $path;
        }


        /**
         * create the key pair,save the key to $this->_keyPath
         */
        public function createKey()
        {
                $r = openssl_pkey_new();
                openssl_pkey_export($r, $privKey);
                file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR . 'priv.key', $privKey);
                $this->_privKey = openssl_pkey_get_public($privKey);


                $rp = openssl_pkey_get_details($r);
                $pubKey = $rp['key'];
                file_put_contents($this->_keyPath . DIRECTORY_SEPARATOR .  'pub.key', $pubKey);
                $this->_pubKey = openssl_pkey_get_public($pubKey);
        }


        /**
         * setup the private key
         */
        public function setupPrivKey()
        {
                if(is_resource($this->_privKey)){
                        return true;
                }
                $file = $this->_keyPath . DIRECTORY_SEPARATOR . 'private.key';
                $prk = file_get_contents($file);
                $this->_privKey = openssl_pkey_get_private($prk);
                return true;
        }


        /**
         * setup the public key
         */
        public function setupPubKey()
        {
                if(is_resource($this->_pubKey)){
                        return true;
                }
                $file = $this->_keyPath . DIRECTORY_SEPARATOR .  'public.key';
                $puk = file_get_contents($file);
                $this->_pubKey = openssl_pkey_get_public($puk);
                return true;
        }


        /**
         * encrypt with the private key
         */
        public function privEncrypt($data)
        {
                if(!is_string($data)){
                        return null;
                }


                $this->setupPrivKey();


                $r = openssl_private_encrypt($data, $encrypted, $this->_privKey);
                if($r){
                        return base64_encode($encrypted);
                }
                return null;
        }


        /**
         * decrypt with the private key
         */
        public function privDecrypt($encrypted)
        {
                if(!is_string($encrypted)){
                        return null;
                }


                $this->setupPrivKey();


                $encrypted = base64_decode($encrypted);


                $r = openssl_private_decrypt($encrypted, $decrypted, $this->_privKey);
                if($r){
                        return $decrypted;
                }
                return null;
        }


        /**
         * encrypt with public key
         */
        public function pubEncrypt($data)
        {
                if(!is_string($data)){
                        return null;
                }


                $this->setupPubKey();


                $r = openssl_public_encrypt($data, $encrypted, $this->_pubKey);
                if($r){
                        return base64_encode($encrypted);
                }
                return null;
        }


        /**
         * decrypt with the public key
         */
        public function pubDecrypt($crypted)
        {
                if(!is_string($crypted)){
                        return null;
                }


                $this->setupPubKey();


                $crypted = base64_decode($crypted);


                $r = openssl_public_decrypt($crypted, $decrypted, $this->_pubKey);
                if($r){
                        return $decrypted;
                }
                return null;
        }


        public function __destruct()
        {
                @ fclose($this->_privKey);
                @ fclose($this->_pubKey);
        }


}



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奇葩也是花

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值