PHP-RSA加密解密

mark下,因为公司项目服务器是用Ruby写的,用的是RSA加密,就尝试下用PHP去读取。T.T,感觉PHP写法比iOS简单多了。


    

 
 0) {
 
        if ($inputLen - $offSet > $maxDecryptBlock) {
            $cache = $method($key, substr($data, $offSet, $maxDecryptBlock));
        } else {
            $cache = $method($key, substr($data, $offSet, $inputLen - $offSet));
        }
        $en = $en . $cache;
 
        $i++;
        $offSet = $i * $maxDecryptBlock;
    }
    return bin2hex($en); //二进制转十六进制
}

function rsa_decrypt($method, $key, $data, $rsa_bit = 1024) {
    $data = pack('H*',$data); //十六进制字符串转二进制
    $inputLen = strlen($data);
    $offSet = 0;
    $i = 0;
 
    $maxDecryptBlock = $rsa_bit / 8;
 
    $de = '';
    $cache = '';
 
    // 对数据分段解密
    while ($inputLen - $offSet > 0) {
 
        if ($inputLen - $offSet > $maxDecryptBlock) {
            $cache = $method($key, substr($data, $offSet, $maxDecryptBlock));
        } else {
            $cache = $method($key, substr($data, $offSet, $inputLen - $offSet));
        }

        $de = $de . $cache;
 
        $i = $i + 1;
        $offSet = $i * $maxDecryptBlock;
    }

    return $de;
}



$pubk = '-----BEGIN PUBLIC KEY-----
xxx
-----END PUBLIC KEY-----';


        $url = 'http://xxx.com/login';
        $post_data['name']      = 'admin';
        $post_data['pwd']       = 'admin';
        $o = "";
        foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $post_data = rsa_encrypt('rsa_publickey_encrypt', $pubk, $post_data);
        echo 'post_data='.$post_data.'
'; $res = request_post($url, $post_data); $de = rsa_decrypt('rsa_publickey_decrypt', $pubk, $res); echo "de=".$de.'
'; /** * 模拟post进行url请求 * @param string $url * @param string $param */ function request_post($url = '', $param = '') { if (empty($url) || empty($param)) { return false; } $postUrl = $url; $curlPost = $param; $ch = curl_init();//初始化curl curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页 curl_setopt($ch, CURLOPT_HEADER, 0);//设置header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上 curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost); $headers = array(); $headers[] = 'X-ANFAN-PRODUCTID: 2'; $headers[] = 'X-ANFAN-RETAILER: 1'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $data = curl_exec($ch);//运行curl curl_close($ch); return $data; }

你可能感兴趣的:(PHP-RSA加密解密)